Get signal level of the connected WiFi network - c

Using wpa_supplicant 2.4 on ARM Debian.
Is there a way to get signal level, in decibels or percents, of the wireless network I’m currently connected to?
STATUS command only returns the following set of values: bssid, freq, ssid, id, mode, pairwise_cipher, group_cipher, key_mgmt, wpa_state, ip_address, p2p_device_address, address, uuid
I can run SCAN afterwards, wait for results and search by SSID. But that’s slow and error-prone, I'd like to do better.
The driver should already know that information (because connected, and adjusting transmit levels for energy saving), is there a way to just query for that?
This question is not about general computing hardware and software. I'm using wpa_supplicant through a C API defined in wpa_ctrl.h header, interacting with the service through a pair of unix domain sockets (one for commands, another one for unsolicited events).
One reason I don’t like my current SCAN + SCAN_RESULT solution, it doesn’t work for hidden SSID networks. Scan doesn’t find the network, therefore I’m not getting signal level this way. Another issue is minor visual glitch at application startup. My app is launched by systemd, After=multi-user.target. Unless it’s the very first launch, Linux is already connected to Wi-Fi by then. In my app’s GUI (the product will feature a touch screen), I render a phone-like status bar, that includes WiFi signal strength icon. Currently, it initially shows minimal level (I know it's connected because STATUS command shows SSID), only after ~1 second I’m getting CTRL-EVENT-SCAN-RESULTS event from wpa_supplicant, run SCAN_RESULT command and update signal strength to the correct value.
On the API level my code is straightforward. I have two threads for that, both call wpa_ctrl_open, the command thread calls wpa_ctrl_request, the event thread has an endless loop that calls poll passing wpa_ctrl_get_fd() descriptor and POLLIN event mask, followed by wpa_ctrl_pending and wpa_ctrl_recv.
And here's the list of files in /sys/class/net/wlan0:
./mtu
./type
./phys_port_name
./netdev_group
./flags
./power/control
./power/async
./power/runtime_enabled
./power/runtime_active_kids
./power/runtime_active_time
./power/autosuspend_delay_ms
./power/runtime_status
./power/runtime_usage
./power/runtime_suspended_time
./speed
./dormant
./name_assign_type
./proto_down
./addr_assign_type
./phys_switch_id
./dev_id
./duplex
./gro_flush_timeout
./iflink
./phys_port_id
./addr_len
./address
./operstate
./carrier_changes
./broadcast
./queues/rx-0/rps_flow_cnt
./queues/rx-0/rps_cpus
./queues/rx-1/rps_flow_cnt
./queues/rx-1/rps_cpus
./queues/rx-2/rps_flow_cnt
./queues/rx-2/rps_cpus
./queues/rx-3/rps_flow_cnt
./queues/rx-3/rps_cpus
./queues/tx-0/xps_cpus
./queues/tx-0/tx_maxrate
./queues/tx-0/tx_timeout
./queues/tx-0/byte_queue_limits/limit
./queues/tx-0/byte_queue_limits/limit_max
./queues/tx-0/byte_queue_limits/limit_min
./queues/tx-0/byte_queue_limits/hold_time
./queues/tx-0/byte_queue_limits/inflight
./queues/tx-1/xps_cpus
./queues/tx-1/tx_maxrate
./queues/tx-1/tx_timeout
./queues/tx-1/byte_queue_limits/limit
./queues/tx-1/byte_queue_limits/limit_max
./queues/tx-1/byte_queue_limits/limit_min
./queues/tx-1/byte_queue_limits/hold_time
./queues/tx-1/byte_queue_limits/inflight
./queues/tx-2/xps_cpus
./queues/tx-2/tx_maxrate
./queues/tx-2/tx_timeout
./queues/tx-2/byte_queue_limits/limit
./queues/tx-2/byte_queue_limits/limit_max
./queues/tx-2/byte_queue_limits/limit_min
./queues/tx-2/byte_queue_limits/hold_time
./queues/tx-2/byte_queue_limits/inflight
./queues/tx-3/xps_cpus
./queues/tx-3/tx_maxrate
./queues/tx-3/tx_timeout
./queues/tx-3/byte_queue_limits/limit
./queues/tx-3/byte_queue_limits/limit_max
./queues/tx-3/byte_queue_limits/limit_min
./queues/tx-3/byte_queue_limits/hold_time
./queues/tx-3/byte_queue_limits/inflight
./tx_queue_len
./uevent
./statistics/rx_fifo_errors
./statistics/collisions
./statistics/rx_errors
./statistics/rx_compressed
./statistics/rx_dropped
./statistics/tx_packets
./statistics/tx_errors
./statistics/rx_missed_errors
./statistics/rx_over_errors
./statistics/tx_carrier_errors
./statistics/tx_heartbeat_errors
./statistics/rx_crc_errors
./statistics/multicast
./statistics/tx_fifo_errors
./statistics/tx_aborted_errors
./statistics/rx_bytes
./statistics/tx_compressed
./statistics/tx_dropped
./statistics/rx_packets
./statistics/tx_bytes
./statistics/tx_window_errors
./statistics/rx_frame_errors
./statistics/rx_length_errors
./dev_port
./ifalias
./ifindex
./link_mode
./carrier

You can get the signal level of the connected wifi by wpa_supplicant cmd SIGNAL_POLL
The wpa_supplicant would return:
RSSI=-60
LINKSPEED=867
NOISE=9999
FREQUENCY=5745
The value of the RSSI is the signal level.
You can get the signal level of the connected wifi by wpa_supplicant cmd BSS <bssid>.
About the bssid of the connected wifi, you can get from wpa_supplicant cmd STATUS.
https://android.googlesource.com/platform/external/wpa_supplicant_8/+/622b66d6efd0cccfeb8623184fadf2f76e7e8206/wpa_supplicant/ctrl_iface.c#1986

For iw compatible devices:
Following command gives the current station(aka AP) signal strength:
iw dev wlp2s0 station dump -v
If you need C API, just dig the source code of iw.
After a quick glance, the function you need is here
For broadcom devices, try search broadcom wl. It is close source, don't know if C API is provided.

Related

How to send Sysrq programmatically over serial and is CONFIG_MAGIC_SYSRQ_SERIAL required

I keep getting the SysRq HELP printout, basically seems i can send over serial the sysrq but it won't accept the next key within 5 seconds ie the command key (b) to reboot.
I need to send the command programmatically over serial console connection to reboot system.
I can reboot the system via echo b > /proc/sysrq-trigger and cat /proc/sys/kernel/sysrq is 1 (ie full sysrq is enabled)
But I notice that kernel (2.6.32) image I'm booting with only has CONFIG_MAGIC_SYSRQ=y and there's no mention of CONFIG_MAGIC_SYSRQ_SERIAL. I'd like to know if that setting is required for 2.6.32 or if it was "assumed enabled" and its only required in new kernels.
According to this, I don't need that in my kernel since it was only added to apparently optionally disable sysrq over serial to prevent unwanted triggers.
Anyway I don't really care if PERL is used or PYTHON or C code with tcsendbreak or any programmatic method to send alt-sysrq-b over /dev/ttyUSB0 to reboot linux over serial. So far all i can do is send break sequence and see output of:
SysRq : HELP : loglevel(0-9) reBoot Crash terminate-all-tasks(E) memory-full-oom
l-active-cpus(L) show-memory-usage(M) nice-all-RT-tasks(N) powerOff show-registe
-blocked-tasks(W)
But the command key sent afterward never does anything. So I'm not sure what's wrong. FYI, the system I'm trying to send sysrq over serial to is an embedded linux system that boots via uboot with uimage and dtb file.
Instead of using a break signal I would prefer a technique where the code actually sends the Alt-SysRq-b keyboard keys over the serial console connection.

GSM Telit GL865-QUAD AT command, error: 314 (SIM card busy)

I'm trying to communicate with GSM click module (Telit GL865-QUAD module) via UART with AT command. First I want to read all received messages, but for some reason I got error 314, meaning that SIM card is busy. Other answers from GSM are ok.
So this is my config (sending few at commands in a row):
AT\r\n (check GSM)
ATE0\r\n (echo disable)
AT+CMGF=1\r\n (set SMS text mode)
AT+IPR?\r\n (query current baud rate)
AT+CMGL=\"ALL\"\r\n (finally read all messages)
All commands have 1 second delay after gsm get positive (OK) answer. For example: send AT\r\n wait for OK and then wait 1 second; after that delay send another AT command.
Result: I got fine response from GSM when I sent first 4 AT command. But after the fifth one the modem returns error 310 (sometimes) followed by error 314:
AT+CMGL="ALL"
+CMS ERROR: 310
AT+CMGL="ALL"
+CMS ERROR: 314\r\n
I tried it with 2 different SIM cards and got same result.
Any idea or comment are welcome.
First of all, GE865-QUAD is an old device, so I recommend that you at least update it to the latest FW version. You can query current FW version of any GSM modem by issuing AT+CGMR AT command.
Edit: since you have a really old version (10.00.144 is dated 2009/2010!) I STRONGLY recommend updating it, since many bugs could have been fixed since then. You will be able to get last version from Telit site, and to flash it via UART.
Errors explanation
You seem to obtain error 314 preceeded, sometimes by error 310.
+CMEE Error: 314 means SIM busy, as correctly stated by your question subject
+CMEE Error: 310 means SIM not inserted
Possible solutions
First of all, make sure that the SIM is correctly inserted. It has to be pushed all its way in. I suppose you correctly inserted it, but a check has to be done.
Then, since you state that
I try with 2 sim cards and got same result.
I suggest you to check the contacts of the SIM holder (because it is unlikely that both your SIMs have bad electric contacts). In fact the SIM busy status, usually reached when a SIM is actually read (e.g. full phonebook) could also mean that some unconsistent action happened (also SIM failure massage can be shown in those cases).
Make sure you wait enough for SIM ready. In fact, even if SIM initialization usually takes less than a second, in some old SIM models might happen that a longer time is needed.
Telit provides a command to query SIM status: AT#QSS. As descripted by the AT guide, it enables an unsolicited message for any SIM status change. But it also allows allows, through its read command to query the status asynchronously:
AT#QSS?
Read command reports whether the unsolicited indication #QSS is currently enabled or not, along with the SIM status, in the format:
#QSS: mode,status
mode - the verbosity level of #QSS URC, set with AT#QSS=mode. Default value is 0; 2 enables the maximum verbosity level.
status - current SIM status
0 - SIM NOT INSERTED
1 - SIM INSERTED
2 - SIM INSERTED and PIN UNLOCKED (Note: available only if mode=2!)
3 - SIM INSERTED and READY (SMS and Phonebook access are possible) (Note: available only if mode=2!)
So you have to wait until status 3 is reached. I suggest issuing read command every 1/2 seconds until the desired status is reached. Issuing commands that involve the SIM storage before that status is reached will lead to SIM Busy error.
Very important: since status=3 will be shown only with mode=2, issue the following concatenated AT command in order to discover if the SIM INSERTED and READY status has been actually received without enabling URCs:
AT#QSS=2;#QSS?;#QSS=0
In this way, mode=2 is set just before the read command so that the full status list is supported. Then mode is restored to value 0, avoiding URCs to appear.
Make sure that the PIN has been inserted!
The SIM could be locked with the PIN code. Verify it by querying AT+CPIN?. If the response is +CPIN: SIM Ready you are fine. Otherwise, If the response is +CPIN: SIM PIN, you have to insert the PIN code by issuing
AT+CPIN=<PIN>
I found what was problem. Power supply for GSM did not have enough Amps.. For GSM you must provide 3.3V and 3A from power supply unit. GSM don't have 6.5W power consumption if you think that GSM need 3A all the time. GSM have peaks of current up to 2A and thats why you need more Amps.

Passive wifi scan with ioctl on linux

I can perform normal scan using ioctl SIOCSIWSCAN and SIOCGIWSCAN and get list of AP, but when I set card into monitor mode i get errno = Operation not supported.
Is there a different ioctl call for passive scans??
I know the wifi card is not the issue, because I get results with airodump-ng and I checked two different cards.
First, on the command line type:
iw phy <phy> info
and see if new_interface is listed under supported commands. You can get the phy for your cards by:
iw dev
Second, I have found that it's easier to set a card in monitor mode if I delete all interfaces on the phy first. Some cards don't play well if there are interfaces active.
Use ioctl to bring cards up or down and to get the card's hw addr. Otherwise you should be using netlink - You're looking for NL80211_CMD_NEW_INTERFACE in nl80211.h

Close device/socket in VxWorks

Is there a way to close the device/socket in VxWorks programmatically?
Meaning say I have the devices /tyco/0, /tyco/1 and /tyco/2 and I want to close/shutdown /tyco/1 and /tyco/2.
I would like to do something like remove("/tyco/1"). Something that would prevent even an open("/tyco/1") call later on in the code or from an outside source from opening the socket.
All devices available to VxWorks are part of the device list. The device list is accessible using the iosLib.
I've used the following code a lot to remove devices to generate errors in order to test my programs:
DEV_HDR *pDevice;
pDevice = iosDevFind("/xyz", NULL);
if (pDevice != NULL)
{
iosDevDelete(pDevice);
}
This works for all devices listed by the devs command which in your case will also work for "/tyco". I doubt that you can inhibit open calls to "/tyco/1" and "/tyco/2" but allow calls to "/tyco/0" using that method since it works on "devices".
If "/tyco/0" is your serial interface to the VxWorks shell then the method from above will work. Because removing a device from the device list will cause all following open calls to that device to fail but will not close already opened devices...

write custom timestamp into syslog using syslog.h

my program get events from remote systems, every event contains an timestamp.
I want to log this events to syslog using the event timestamp instead of systemtime.
Is there any way to send a custom header to syslog deamon ?
I'm using rsyslog on debian
EDIT:
The "events" are generated by some "bare-metal" devices.
My application is a gateway between a realtime-ethernet (EthernetPOWERLINK) and a normal network.
I want to save them in micro-second precision, because its important to know in wich sequence they are occoured.
So i need the exact timestamp created by the bare-metal devices.
I'like to put this events into syslog.
I did not found any lib (except syslog.h) to write into syslog).
I really need to build the packages myself and send them to rsyslog deamon ?
No, don't open that can of worms.
If you allow the sender to specify the timestamp, you allow an attacker to spoof the timestamps of events they wish to hide. That kind of defeats the entire purpose (security-wise) of using a separate machine for logging.
What you can do, however, is compare the current time and the timestamp, and include that at the start of every logged message, using something like
struct timespec now;
struct timespec timestamp;
double delta;
int priority = facility | level;
const char *const message;
delta = difftime(timestamp.tv_sec, now.tv_sec)
+ ((double)timestamp.tv_nsec - now.tv_nsec) / 1000000000.0;
syslog(priority, "[%+.0fs] %s\n", delta, message);
On a typically configured Linux machine, that should produce something similar to
Jan 18 08:01:02 hostname service: [-1s] Original message
assuming the message took at least half a second to arrive. If hostname has its clock running fast, the delta would be positive. Normally, the delta is zero. In the case of a very slow network, the delta is negative, since the original event happened in the past relative to the timestamp shown.
If you already have infrastructure in place to monitor the logged messages, you can have a daemon or a cron script read the log files, and generate new log files (not via syslog(), but simply with string and file operations) with the timestamps adjusted by the specified delta. However, that must be done with extreme care, recognizing unacceptable or unexpectedly changing deltas, or maybe flagging them somehow.
If you write your log file monitoring/display widgets, then you can very easily let the user switch between "actual" (syslog) or "derived" (syslog + delta) timestamps, as the delta is trivial to extract from the logged lines if always present; even then, you must be careful to let the user know if a delta is out of bounds or changes unexpectedly, as such a change is most always informative to the user. (If it is not nefarious, it does mean there is something iffy with the machine timekeeping; time should not just jump around. Even NTP adjustments should be quite smooth.)
If you insist on opening that can of worms, just produce your own log files. Many applications do. It's not like syslog() was a magic bullet or a strict requirement for reliable logging, after all.
If your log-receiving application runs as a specific user and group, you can create /var/log/yourlogs/ owned by root user and that group, and save your log files there. Set the directory mode to 02770 (drwxrws--- or u=rwx,g=rwxs,o=), and all files created in that directory will automatically be owned by the same group (that's what the setgid bit, s, does for directories). You just need to make sure your service sets umask to 002 (and uses 0666 or 0660 mode flags when creating log files), so that they stay group-readable and group-writable.
Log rotation (archiving and/or deleting old log files, mailing logs) is usually a separate service, provided by the logrotate package, and configured by dropping a service-specific configuration file in /etc/logrotate.d/ at installation time. In other words, even if you write your own log files, do not rotate them; use the existing service for this. It makes life much easier for your users, us system administrators. (Note: Setting umask 002 at the start of the log rotate scripts is very useful in the above directory case; created files will then be group-writable. umask 022 will make them group-read-only.)
Ok've solved this, by enabling networking support (TCP) and micro seconds timer in rsyslog configuration.
Accroding to RFC 5424 my application build raw syslog messages and sends them via TCP (port 514) to the deamon.
Thanks to Nominal Animal, but i've no choice...
You can write a raw log message to the /dev/log file. This is a Unix domain socket from where the syslog server reads the messages, as they are written with the syslog() function.
I'm not sure about portability since the message format written by syslog() does not seem to follow the RFC 5424. I can only share my findings with busybox and its syslogd and nc utilities.
syslog() function writes messages as datagrams in the form <PRI>Mon DD HH:MM:SS message, where PRI is a priority, i.e. a decimal number computed as facility | severity, followed by a timestamp and a message.
With nc -u local:/dev/log, you can write UDP datagrams to the domain socket directly. For example, writing <84>Apr 3 07:27:20 hello world results in a Apr 3 07:27:20 hostname authpriv.warn hello world line in /var/log/messages.
Then you are free to extend the timestamp with the microseconds precision. Anyway, you need to make sure your syslog server implementation accepts such form. In case of busybox, I had to modify the source code.
Note: Busybox needs to be configured with enabled CONFIG_NC_EXTRA, CONFIG_NC_110_COMPAT and CONFIG_FEATURE_UNIX_LOCAL options to allow for opening /dev/log with nc.

Resources