3 Haziran 2021 Perşembe

National Maritime Electronics Association - NMEA Navtex Mesajları

Giriş
Navtex cihazını şu mesajlarla beslemek gerekir
GPS
RMC - Konum
ZDA - Saat ve Tarih

Navtex cihazından şu mesajlar okunur
1. ALR - Set Alarm State
Cihazdaki alarm durumunu belirtir
Mesaj şöyle
1. Sentence Id
2. Time of alarm condition change, UTC
3. Unique alarm number (identifier) at alarm source
4. Alarm's acknowledge state, A=Acknowledged,V=Unacknowledged
5. Alarm condition, A=Threshold exceeded, V=Notexceeded
6. Alarm description text
2. NRM - Navtex Receiver Mask Command
Mesaj şöyle. Hem input hem de output için kullanılabilir.
1. Sentence Id
2. Function code, 0 to 9
3. Frequency table index, 1 to 9
4. Transmitter coverage area mask
5. Message type mask
6. Sentence status flag, R or C

3. NRX - Navtex Received Message
Açıklaması şöyle
The NRX sentence is used to transfer the contents of a received NAVTEX message from the NAVTEXreceiver to another device. As the length of a single NAVTEX message may exceed the number of characters permitted in a single NMEA 0183 sentence, many NRX sentences may be required to transfer a single NAVTEX message.
Mesaj şöyle
1. Sentence Id
2. Total number of sentences, 001 to 999
3. Sentence number, 001 to 999
4. Sequential message id, 00 to 99
5. NAVTEX message code
6. Frequency table index, 0 to 9
7. UTC of receipt of message
8. Day, 1 to 31
9. Month, 1 to 12
10. Year
11. Total number of characters in this series of NRXsentences
12. Total number of bad characters
13. Status indication
14. Message body
4. alan olan Sequential Message Id için açıklama şöyle. Aslında 5. alan olan NAVTEX message code alanının kullanılmaması söyleniyor. Bu alan cümleleri birleştirirken kullanılıyor.
The sequential message identifier provides a unique identifier for each NAVTEX message represented by a group of sentences.

Though the message code contains a NAVTEX message serial number, there are special cases when the message serial number is set to 00 and has a different meaning or when the same message code can occur more than once. When these conditions occur, the sequential message identifier can be relied upon to uniquely identify this NAVTEX message from other NAVTEX messages with the same message code.
6. alan olan Frequency Table Index için açıklama şöyle
The frequency indicator identifies the frequency that the NAVTEX message was
received on:
0 = not received over air (eg test messages)
1 = 490 kHz
2 = 518 kHz
3 = 4209,5 kHz
4 through 9 are reserved for future use 
14. alan olan message body "c - c Calculated"  olarak işaretli. IEC 61162-1 Table 2'deki karakterlere göre çevrilmeli. Böylece her karakter için 1 byte harcanıyor

Örnek
Bir örnek şöyle. ^0D^0A "new line" demek. ^0A^0A mesaj sonu demek
The example below shows a typical message received by the Navtex receiver with 3 bad characters (‘*’):

<start of example>
ZCZC IE69==================================
ISSUED ON SATURDAY 06 JANUARY 2001.
INSHORE WATERS FORECAST TO 12 MILES
OFFSHORE FROM 1700 UT* TO 0500 UTC.
NORTH FORELAND TO SE**EY BILL.
12 HOURS FORECAST:
SHOWERY WINDS, STRONGEST IN NORTH.
NNNN
<end of example>

Inspecting the corresponding NRX sentences would typically show:
$CRNRX,007,001,00,IE69,1,135600,27,06,2001,241,3,A,==========================*09
$CRNRX,007,002,00,,,,,,,,,,========^0D^0AISSUED ON SATURDAY 06 JANUARY 2001.*29
$CRNRX,007,003,00,,,,,,,,,,^0D^0AINSHORE WATERS FORECAST TO 12 MILES^0D^0AOFF*0D
$CRNRX,007,004,00,,,,,,,,,,SHORE FROM 1700 UT^2A TO 0500 UTC.^0D^0A^0D^0ANORT*70
$CRNRX,007,005,00,,,,,,,,,,H FORELAND TO SE^2A^2AEY BILL.^0D^0A12 HOURS FOREC*16
$CRNRX,007,006,00,,,,,,,,,,AST:^0D^0A^0ASHOWERY WINDS^2C STRONGEST IN NORTH.^0D*15
$CRNRX,007,007,00,,,,,,,,,,^0A^0A*79

Decoding the message body should give the following result:

<start of decoding>
==================================
ISSUED ON SATURDAY 06 JANUARY 2001.
INSHORE WATERS FORECAST TO 12 MILES
OFFSHORE FROM 1700 UT* TO 0500 UTC.
NORTH FORELAND TO SE**EY BILL.
12 HOURS FORECAST:
SHOWERY WINDS, STRONGEST IN NORTH.
<end of decoding> 
Aynı örnek şöyle
$CRNRX,007,001,00,TD02,1,135600,27,06,2001,241,3,A,==========================*09
$CRNRX,007,002,00,,,,,,,,,,========^0D^0AISSUED ON SATURDAY 06 JANUARY 2001.*29
$CRNRX,007,003,00,,,,,,,,,,^0D^0AINSHORE WATERS FORECAST TO 12 MILES^0D^0AOFF*0D
$CRNRX,007,004,00,,,,,,,,,,SHORE FROM 1700 UTC TO 0500 UTC.^0D^0A^0D^0ANORT*70
$CRNRX,007,005,00,,,,,,,,,,H FORELAND TO SELSEY BILL.^0D^0A12 HOURS FOREC*16
$CRNRX,007,006,00,,,,,,,,,,AST:^0D^0A^0ASHOWERY WINDS, STRONGEST IN NORTH.^0D*15
$CRNRX,007,007,00,,,,,,,,,,^0A^0A*79


2 Haziran 2021 Çarşamba

Redis Data Eviction

Giriş
Açıklaması şöyle
Can store the details to disk when the physical memory is fully occupied. Redis has the mechanism to swap the values that are least recently used to disk and the latest values into the physical memory.
Supported Eviction Policies
Açıklaması şöyle. LFU kısaltması Least Frequently Used, LRU kısaltması Least Recently Used anlamına gelir.
- No Eviction (Returns an error if the memory limit has been reached when trying to insert more data) Least Recently Used (LRU)
-All keys LRU (Evicts the least recently used keys out of all keys)
-Volatile LFU (Evicts the least frequently used keys out of all keys)
-All keys random (Randomly evicts keys out of all keys)
-Volatile random (Randomly evicts keys with an “expire” field set)
-Volatile TTL (Evicts the shortest time-to-live and least recently used keys out of all keys with an “expire” field set.)
-volatile LRU (Evicts the least recently used keys out of all keys with an “expire” field set)
-volatile LFU (Evicts the least frequently used keys out of all keys with an “expire” field set)
Açıklaması şöyle
Redis comprises several data eviction engines:

TTL - object eviction as soon as their lifetime expires;

LRU - long used data eviction;

RANDOM - random object eviction;

LFU - rarely used data eviction.
TTL İçin Expiration Event
Açıklaması şöyle. Yani Expiration Event gelmesi garanti edilen bir şey değil
In the field of e-commerce, payments, etc., there are often such scenarios, the user placed an order and then abandoned the payment, that order will be closed after a specified period of time operation, careful you must have found like a certain treasure, a certain east have such logic, and the time is very accurate, the error is within 1s; then how do they achieve it?
There are several general ways to implement this.

1. using the delayed cast feature of message queues such as rocketmq, rabbitmq, pulsar, etc.
2. using the DelayedQueue provided by redisson.

There are some solutions that are widely spread but have fatal flaws and should not be used to implement delayed tasks.

1. using redis’ expired listeners.
2. using rabbitmq’s dead letter queue.
3. using a non-persistent time wheel.
Redis'in resmi açıklaması şöyle
Basically expired events are generated when the Redis server deletes the key and not when the time to live theoretically reaches the value of zero
Redis'in gerçekleştirimi için  açıklama şöyle
The redis auto-expiration is implemented as a timed task that scans offline and removes partially expired keys; it inertly checks for expiration and removes expired keys when they are accessed. redis is never guaranteed to remove and send expiration notifications immediately at the set expiration time. In fact, it is not uncommon for expiration notifications to be several minutes later than the set expiration time.

In addition, keyspace notifications are sent using a fire and forget policy and are not guaranteed to be delivered like message queues. When a client subscribes to an event, it loses all events that were distributed to it during the disconnect.
Örnek
Şöyle yaparız
const { createClient } = require('redis');
const client = createClient({
    host: process.env.REDIS_ENDPOINT || 'localhost',
    port: process.env.REDIS_PORT || 6379
});
if (process.env.REDIS_PASSWORD) {
    client.auth(process.env.REDIS_PASSWORD);
}
client.config('set', 'notify-keyspace-events', 'Ex');
client.subscribe('__keyevent@0__:expired');
client.on('message', function (channel, key) {
    console.log(key);
});
Ancak burada dikkat edilmesi gereken bazı noktalar var. Açıklaması şöyle. Yani event tam vaktinde gelmek zorunda değil ve Redis cluster şeklinde çalışıyorsa, tüm düğümlere abone olmak gerekir.
- There are no guarantees that the Redis server will be able to generate the expired event at the time the key time to live reaches the value of zero
- expired events are generated when the Redis server deletes the key and not when the time to live theoretically reaches the value of zero.
- Pub/Sub communication in a cluster, events notifications are not broadcasted to all nodes.

Redis Transaction

Giriş
Açıklaması şöyle
The concept of transaction in Redis is very different from its counterpart in traditional RDBMS. A client can submit an operations sequence to a Redis server as a transaction. The Redis server will guarantee the sequence is executed as an atomic unit without changing context to serve other requests, until the transaction is finished. However, unlike an RDBMS, if one of the steps in the sequence fails, Redis will not roll back the entire transaction. 
...
Furthermore, a Redis cluster can only support transactions if the sequence of operations works on data structures in the same shard.
Açıklaması şöyle.
Redis offers two mechanisms for handling transactions – MULTI/EXEC based transactions and Lua scripts evaluation. Redis Lua scripting is the recommended approach and is fairly popular in usage.
MULTI ve EXEC
Kullanılan komutlar şöyle
MULTI - begin transaction
EXEC - commit transaction
DISCARD - rollback transaction
WATCH - prevent committing the current transaction if some keys are changed outside the current transaction
UNWATCH - cancel the watching process on the related key
Örnek
Şöyle yaparız
> MULTI
OK
> INCR foo
QUEUED
> INCR bar
QUEUED
> EXEC
1) (integer) 1
2) (integer) 1
OLAP
Açıklaması şöyle
Both Redis and Tarantool are poorly tailored for OLAP tasks. Online Analytical Processing deals with historic or archive data. OLAP has relatively few transactions, queries are often complex and contain aggregation.

In both cases, data is stored line-by-line. This makes aggregation algorithms less effective as compared to column-oriented databases.

Redis and Tarantool use one-thread for data which makes parallelizing analytical queries impossible.

Redis Data Persistence (Veri Kalıcılığı)

Giriş 
4 çeşit persistence özelliği sağlar. Açıklaması şöyle
So Redis provides a different range of persistence options:
- RDB (Redis Database): The RDB persistence performs point-in-time snapshots of your dataset at specified intervals.
- AOF (Append Only File): The AOF persistence logs every write operation received by the server, that will be played again at server startup, reconstructing the original dataset. Commands are logged using the same format as the Redis protocol itself, in an append-only fashion. Redis is able to rewrite the log in the background when it gets too big.
- No persistence: If you wish, you can disable persistence completely, if you want your data to just exist as long as the server is running.
- RDB + AOF: It is possible to combine both AOF and RDB in the same instance. 
Bu 4 taneden sadece 2 tanesi diske bir şey yazar. Bunlar
1. Snapshot (Anlık Durum)
2. Append Only File (AOF)
Açıklaması şöyle
Redis supports two modes of file system persistence — append-only file (AOF) and snapshotting (RDB):
1. Snapshot Persistence
Açıklaması şöyle. Anlık Durum veri kalıcılığı ile belli aralıklarda veri kaydedilir. İki kayıt zamanı arasındaki veri kaybolabilir.
It saves data in one of the following cases:
- automatically from time to time
- when redis is shutting down
Bazı avantajlar şöyle. Eğer dosya arşivlenmişse geçmişteki bir ana gidebilmek mümkün.
RDB advantages :
- RDB is a very compact single-file point-in-time representation of your Redis data. RDB files are perfect for backups. For instance, you may want to archive your RDB files every hour for the latest 24 hours and to save an RDB snapshot every day for 30 days. This allows you to easily restore different versions of the data set in case of disasters.
- RDB is very good for disaster recovery, being a single compact file that can be transferred to far data centers.
- RDB allows faster restarts with big datasets compared to AOF
Dosya ismi şöyle
By default Redis saves snapshots of the dataset on disk, in a binary file called dump.rdb. You can configure Redis to have it save the dataset every N seconds if there are at least M changes in the dataset, or you can manually call the SAVE or BGSAVE commands.
Kaydetme sıklığı şöyle. Yani sabit bir periyodda çalışmıyor
So Redis stores snapshots of your data to disk in a dump.rdb file in the following conditions:
- Every minute if 1000 keys were changed
- Every 5 minutes if 10 keys were changed
- Every 15 minutes if 1 key was changed

So if you’re doing heavy work and changing lots of keys, then a snapshot per minute will be generated for you, in case your changes are not that much then a snapshot every 5 minutes, if it’s really not that much then every 15 minutes a snapshot will be taken.
2. Append Only File Persistence
Açıklaması şöyle
- Append-only file is similar to write-ahead logs employed by SQL databases that record each mutating operation to a file that can be played back at database start to recover the data.
Bu özelliği etkinleştirmek için konfigürasyon dosyasında şöyle yaparız
appendonly yes
fsync seçenekeri şöyle
As we explained in AOF section we have the following options for durability levels

appendfsync always: fsync every time new commands are appended to the AOF. Very very slow, very safe. Note that the commands are appended to the AOF after a batch of commands from multiple clients or a pipeline are executed, so it means a single write and a single fsync (before sending the replies).

appendfsync everysec: fsync every second. Fast enough (in 2.4 likely to be as fast as snapshotting), and you can lose 1 second of data if there is a disaster.

appendfsync no: Never fsync, just put your data in the hands of the Operating System. The faster and less safe method. Normally Linux will flush data every 30 seconds with this configuration, but it's up to the kernel exact tuning.
appendfsync everysec Seçilirse
1 saniye yerine 2 saniyelik veri kaybedersiniz diyen bir yazı da var. Hangisi doğru bilmiyorum

Bu İkisi Birlikte Kullanılır
Açıklaması şöyle. Aslında ikisi birlikte kullanılınca ne olacağına dair farkı açıklamalar var. Bir açıklama sadece AOF kullanılır diyor, bir diğeri de Snapshot + AOF birlikte kullanılır diyor.
At specified intervals, Redis snapshots all in-memory data. By default, it is done every 60 seconds (customizable). Redis copies the current in-memory data using OS.fork and then stores data to the disk. 

In case of an abnormal shutdown, Redis recovers its status from the most recent saving. If the last snapshot was made a long time ago, all the data received after the snapshot will be lost.

The transaction journal is used to store all the information arriving at the database. Every operation is logged in the on-disk journal. When Redis is started, it recovers its status from the snapshot and then adds the remaining operations from the journal.
Troubleshooting
Açıklaması şöyle
If a journal file is damaged in Redis:

redis-check-aof --fix
Diğer Alternatifler
Redis'in veri kalıcılığı yerine diğer genel çözümler şöyle
Except for kvrocks, the open-source community has some similar disk key-value systems and can divide into three categories:

1. Implement the Redis protocol and replication based on disk key-value engine, like LevelDB, RocksDB, etc…
2. Swap Redis cold keys into the disk storage like Redis on Flash, or the Redis VM in the old version but deprecated now
3. Implement the Redis proxy based on the distributed KV(e.g. TiKV). Data integrity and durability are in the hand of Redis
etcd vs Redis
etcd vs Redis yazısında, Redis'in tam anlamıyla konfigürasyon verisini saklamak için uygun olmadığına dikkat çekiliyor. Burada sanırım en önemli fark, slave düğümlerin master ile sync işlemi başlatmasından kaynaklanıyor. Burada da bir soru var.
etcd vs. Redis
Like etcd, Redis is an open source tool, but their basic functionalities are different.

Redis is an in-memory data store and can function as a database, cache, or message broker. Redis supports a wider variety of data types and structures than etcd and has much faster read/write performance.

But etcd has superior fault tolerance, stronger failover and continuous data availability capabilities, and, most importantly, etcd persists all stored data to disk, essentially sacrificing speed for greater reliability and guaranteed consistency. For these reasons, Redis is better suited for serving as a distributed memory caching system than for storing and distributed system configuration information.

National Maritime Electronics Association - NMEA Navigation Radarı Mesajları

Giriş
Seyir Radarı az sayıda mesaj üretiyor ancak ürettiği mesajları hesaplayabilmek için çok sayıda farklı cihazın çıktısı ile beslemek gerekiyor. Beslemek için kullanılan mesajlar şöyle

Echo Sounder
- Depth Below Transducer
- Depth

GPS
- Datum Reference
- Global Positioning Fix Data
- Geographic Position - Latitude/Longitude
- Course Over Ground and Ground Speed
- Time & Date
Açıklaması şöyle
Is the GPS speed required in RADAR ?
There is no debate that GPS feed is required in Radars for position. But if we have to use speed over water in radar, do we require GPS speed then ?

Yes, we do. 
...
By using speed over ground, a navigator is more aware of the situation than otherwise. For example, if the ship is drifting towards a danger, navigator will know it better if he has speed over ground in radar. This is because, with speed over ground radar will show a vector of course made good.

Meteorological Sensor
- Wind Speed and Angle

Gyro
- Heading True
- Rate Of Turn

Speed Log
- Dual Ground/Water Speed
- Water Speed And Heading

AIS
- VDM
- VDO

1. RATTM - Tracked Target Message
Bağlantı hızı 4800 baud gibi düşük bir şey olduğu için radar tüm izleri aynı anda gönderemez. Genellikle her dönüşte 10-20 gibi bir alt küme gönderir. Böylece mesela toplamda 100 tane iz takip edebiliyorsa, tüm izleri 5 dönüşte bir gönderir. Her dönüş 2 saniye ise, 10 saniyede bir tüm izler aktarılır. Şeklen şöyle
Target number
Distance to target
Bearing from own ship (degrees)
Type of bearing 'T' - true; 
                'R' - the relative

Target speed
Target course (degrees)
Type of course 'T' - true; 
                'R' - the relative


CPA (in miles)         Distance of closest-point-of-approach
TCPA (in min.)         Time to distance of closest-point-of-approach

U measuring speed / distance 'R' - km; 
                'N' - mor. mile; 
                'S' - statute miles

 
Name of target not processed
Status goals
Purpose-binding not processed
UTC time
Type of seizure not processed
Speed/distance units 
- K yani kilometers/hour veya 
- N nautical miles/hour veya 
- S statue miles/hour cinsinden olabilir

ARPA CPA
ARPA plotların ize yani track' dönüşmesi demek. CPA kısaltması Closest Point of Approach anlamına geliyor. ARPA CPA bilgisi için

Target number, Bearing from own ship (degrees),  CPA (mesafe) ve TCPA (saniye cinsinden süre) alanları kullanılır

2. RARSD - Radar System Data
Örnek ver

3. RAOSD - Radar Ownship Data
Şeklen şöyle
Heading, degrees True
Heading Status, A = Data Valid, V = Invalid

Vessel Course, degrees True
Course Reference B/M/W/R/P

Vessel Speed
Speed Reference B/M/W/R/P

Vessel Set, degrees True
Vessel drift (speed)

Speed Units K/N

1 Haziran 2021 Salı

DDS TimeBasedFilter Qos - DataReader İçin Geçerlidir

Giriş
İki tane read() işlemi arasında olması istenen "minimum separation" süresi tanımlanabilir. Böylece eğer DataWriter çok fazla veri gönderiyorsa, bir kısmı süzülür

DDS Ownership Qos - DataWriter İçin Geçerlidir

Giriş
Aynı topic bilgisini gönderen birden fazla publisher varsa, hangisini tercih edileceğini belirtir. OwnershipQosPolicy yapısı kullanılır

kind Alanı
Bir enum'dur. Açıklaması şöyle
OwnershipQosPolicyKind
There are two possible values (see OwnershipQosPolicyKind):

SHARED_OWNERSHIP_QOS: This option indicates that the service does not enforce unique ownership for each instance. In this case, multiple DataWriters are allowed to update the same data instance and all the updates are made available to the existing DataReaders. Those updates are also subject to the TimeBasedFilterQosPolicy or HistoryQosPolicy settings, so they can be filtered.

EXCLUSIVE_OWNERSHIP_QOS: This option indicates that each instance can only be updated by one DataWriter, meaning that at any point in time a single DataWriter owns each instance and is the only one whose modifications will be visible for the existing DataReaders. The owner can be changed dynamically according to the highest strength between the alive DataWriters, which has not violated the deadline contract concerning the data instances. That strength can be changed using the OwnershipStrengthQosPolicy.