Module: BlinkTM

Extended by:
BlinkTM
Included in:
BlinkTM
Defined in:
lib/blink_tm.rb,
lib/blink_tm/version.rb,
lib/blink_tm/blink_tm.rb,
ext/crc32/crc32.c,
ext/baudrate/baudrate.c

Constant Summary collapse

BAUDRATE =

Important Constants

BlinkTM::B38400
SCANID =
'BTM'
POLLING =

POLLING time, how often should CPU, Net, IO usages should be updated. Should always be a float.

0.250
REFRESH =

Refresh time, how often the main loop should run

0.5
NoDeviceError =

Errors

Class.new(StandardError)
SyncError =
Class.new(StandardError)
DeviceNotReady =
Class.new(StandardError)
TB =

Units

10 ** 12
GB =
10 ** 9
MB =
10 ** 6
KB =
10 ** 3
RED =

ANSI Sequences

"\e[38;2;225;79;67m"
BLUE =
"\e[38;2;45;125;255m"
GREEN =
"\e[38;2;40;175;95m"
ORANGE =
"\e[38;2;245;155;20m"
BOLD =
"\e[1m"
RESET =
"\e[0m"
LOCKFILE =
'/tmp/blinktaskmanager.pid'
LOGFILE =
'/tmp/blinktaskmanager.err.log'
ROOT_DEV =

Other constants

::LinuxStat::Mounts.root
ROOT =
File.split(ROOT_DEV)[-1]
SECTORS =
::LS::Filesystem.sectors(ROOT_DEV)
VERSION =
"2.2.0"
B0 =
INT2FIX(B0)
B50 =
INT2FIX(B50)
B75 =
INT2FIX(B75)
B110 =
INT2FIX(B110)
B134 =
INT2FIX(B134)
B150 =
INT2FIX(B150)
B200 =
INT2FIX(B200)
B300 =
INT2FIX(B300)
B600 =
INT2FIX(B600)
B1200 =
INT2FIX(B1200)
B1800 =
INT2FIX(B1800)
B2400 =
INT2FIX(B2400)
B4800 =
INT2FIX(B4800)
B9600 =
INT2FIX(B9600)
B19200 =
INT2FIX(B19200)
B38400 =
INT2FIX(B38400)
B57600 =
INT2FIX(B57600)
B115200 =
INT2FIX(B115200)
@@retry_count =
0

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.baudrate(dev) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'ext/baudrate/baudrate.c', line 58

VALUE getBaudRate(volatile VALUE obj, volatile VALUE dev) {
	char *device = StringValuePtr(dev) ;

	int serial_port = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK) ;
	struct termios tty ;

	char status = tcgetattr(serial_port, &tty) ;
	close(serial_port) ;

	if(status == 0) {
		unsigned int in = cfgetispeed(&tty) ;
		unsigned int out = cfgetospeed(&tty) ;

		return rb_ary_new_from_args(2,
			UINT2NUM(in), UINT2NUM(out)
		) ;
	}

	return rb_ary_new() ;
}

.crc32(str) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'ext/crc32/crc32.c', line 11

static VALUE getCRC(volatile VALUE obj, volatile VALUE str) {
	char *input = StringValuePtr(str) ;
	unsigned char len = strlen(input) ;
	unsigned long crc = 0xFFFFFFFF ;

	for (unsigned char i = 0 ; i < len ; ++i) {
		crc ^= input[i] ;

		for (unsigned char k = 8 ; k ; --k) {
			crc = crc & 1 ? (crc >> 1) ^ CRC32_DIVISOR : crc >> 1 ;
		}
	}

	char buffer[11] ;
	sprintf(buffer, "%lu", crc ^ 0xFFFFFFFF) ;

	return rb_str_new_cstr(buffer) ;
}

.get_baudrate(dev) ⇒ Object



58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'ext/baudrate/baudrate.c', line 58

VALUE getBaudRate(volatile VALUE obj, volatile VALUE dev) {
	char *device = StringValuePtr(dev) ;

	int serial_port = open(device, O_RDWR | O_NOCTTY | O_NONBLOCK) ;
	struct termios tty ;

	char status = tcgetattr(serial_port, &tty) ;
	close(serial_port) ;

	if(status == 0) {
		unsigned int in = cfgetispeed(&tty) ;
		unsigned int out = cfgetospeed(&tty) ;

		return rb_ary_new_from_args(2,
			UINT2NUM(in), UINT2NUM(out)
		) ;
	}

	return rb_ary_new() ;
}

.set_baudrate(dev, speed) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'ext/baudrate/baudrate.c', line 6

VALUE setBaudRate(volatile VALUE obj, volatile VALUE dev, volatile VALUE speed) {
	char *device = StringValuePtr(dev) ;
	unsigned int spd = NUM2UINT(speed) ;

	int serial_port = open(device, O_RDWR | O_NOCTTY) ;
	struct termios tty ;

	char status = tcgetattr(serial_port, &tty) ;

	/*
		Serial Monitor sets these flags:

		speed 57600 baud; line = 0;
		min = 0; time = 0;
		-brkint -icrnl -imaxbel
		-opost
		-isig -icanon -iexten -echo -echoe -echok -echoctl -echoke
	*/

	if(status != 0) {
		close(serial_port) ;
		return Qnil ;
	}

	tty.c_cflag &= ~CSIZE ;
	tty.c_cflag |= CS8 ;
	tty.c_cflag |= CREAD | CLOCAL ;
	tty.c_oflag &= ~OPOST ;

	tty.c_lflag &= ~ECHO ;
	tty.c_lflag &= ~ECHOCTL ;
	tty.c_lflag &= ~ECHOK ;
	tty.c_lflag &= ~ECHOE ;
	tty.c_lflag &= ~ECHOKE ;
	tty.c_lflag &= ~ISIG ;
	tty.c_lflag &= ~ICRNL ;
	tty.c_lflag &= ~IEXTEN ;
	tty.c_lflag &= ~ICANON ;

	tty.c_cc[VTIME] = 0 ;
	tty.c_cc[VMIN] = 0 ;

	cfsetispeed(&tty, spd) ;
	cfsetospeed(&tty, spd) ;
	status = tcsetattr(serial_port, TCSANOW, &tty) ;

	close(serial_port) ;

	if (status == 0) return Qtrue ;
	return Qfalse ;
}

Instance Method Details

#convert_bytes(n) ⇒ Object

Convert Numeric bytes to the format that blink-taskmanager can read



58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/blink_tm/blink_tm.rb', line 58

def convert_bytes(n)
	if n >= TB
		"%06.2f".%(n.fdiv(TB)).split(?.).join + ?4
	elsif n >= GB
		"%06.2f".%(n.fdiv(GB)).split(?.).join + ?3
	elsif n >= MB
		"%06.2f".%(n.fdiv(MB)).split(?.).join + ?2
	elsif n >= KB
		"%06.2f".%(n.fdiv(KB)).split(?.).join + ?1
	else
		"%06.2f".%(n).split(?.).join + ?0
	end
end

#convert_percent(n) ⇒ Object

Convert percentages to the format that blink-taskmanager can read



73
74
75
# File 'lib/blink_tm/blink_tm.rb', line 73

def convert_percent(n)
	"%06.2f".%(n).split('.').join
end

#find_deviceObject

Detect device



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/blink_tm/blink_tm.rb', line 6

def find_device
	Dir.glob('/sys/bus/usb/devices/*').each { |x|
		v = File.join(x, 'idVendor')
		vendor = IO.read(v).strip if File.readable?(v)

		p = File.join(x, 'idProduct')
		product = IO.read(p).strip if File.readable?(p)

		if vendor == '1a86' && product == '7523'
			log 'warn', "A potential device discovered: #{vendor}:#{product}"

			Dir.glob('/dev/ttyUSB[0-9]*').each { |x|
				if File.writable?(x)
					log 'success', "Changing baudrate to 57600..."

					if BlinkTM.set_baudrate(x, BlinkTM::BAUDRATE)
						log 'success', 'Successfully Changed baudrate to 57600...'
					else
						log 'error', 'Cannot change the baudrate'
					end
				else
					log 'error', 'No permission granted to change Baudrate'
				end

				if File.readable?(x)
					begin
						return x if File.open(x).read_nonblock(30).to_s.scrub.include?("BTM")
					rescue EOFError
						sleep 0.05
						retry
					rescue Errno::ENOENT, Errno::EIO
					end
				end
			}
		end
	}

	nil
end

#find_device!Object



47
48
49
50
51
52
53
54
55
# File 'lib/blink_tm/blink_tm.rb', line 47

def find_device!
	while(!(dev = BlinkTM.find_device))
		log 'error', "No device found. Retrying #{@@retry_count += 1}"
		sleep 0.5
	end

	log 'success', "Device discovered successfully. Path: #{dev}#{BlinkTM::RESET}"
	dev
end

#log(type, message = nil) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/blink_tm/blink_tm.rb', line 219

def log(type, message = nil)
	message, type = type, nil if type && !message

	colour = case type
		when 0, 'fatal', 'error' then BlinkTM::RED
		when 1, 'warn' then BlinkTM::ORANGE
		when 2, 'info' then BlinkTM::BLUE
		when 3, 'success', 'ok' then BlinkTM::GREEN
		else ''
	end

	puts "#{BlinkTM::BOLD}#{colour}:: #{Time.now.strftime('%H:%M:%S.%2N')}: #{message}#{BlinkTM::RESET}"
end

#start(device, daylight_checker_options) {|file| ... } ⇒ Object

Yields:

  • (file)

Raises:



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/blink_tm/blink_tm.rb', line 77

def start(device, daylight_checker_options)
	return false unless device

	latitude, longitude = daylight_checker_options[:latitude]&.to_f, daylight_checker_options[:longitude]&.to_f
	log 'success', "Set latitude to #{latitude}, longitude to #{longitude}" if !latitude.nil? && !longitude.nil?

	cpu_u = mem_u = swap_u = iostat = net_u = net_d = 0
	io_r = io_w = 0
	built_in_led_state = 0

	Thread.new {
		while true
			_cpu_u = LS::CPU.total_usage(POLLING).to_f
			cpu_u = _cpu_u.nan? ? 255 : _cpu_u.to_i
		end
	}

	Thread.new {
		while true
			netstat = LS::Net::current_usage(POLLING)
			net_u = netstat[:transmitted].to_i
			net_d = netstat[:received].to_i
		end
	}

	Thread.new {
		while true
			io_stat1 = LS::FS.total_io(ROOT)
			sleep POLLING
			io_stat2 = LS::FS.total_io(ROOT)

			io_r = io_stat2[0].-(io_stat1[0]).*(SECTORS).fdiv(POLLING)
			io_w = io_stat2[1].-(io_stat1[1]).*(SECTORS).fdiv(POLLING)
		end
	}

	prev_crc32 = ''
	prev_time = { min: -1, hour: -1 }
	raise NoDeviceError unless device

	in_sync = false

	fd = IO.sysopen(
		device,
		Fcntl::O_RDWR | Fcntl::O_NOCTTY | Fcntl::O_NONBLOCK | Fcntl::O_TRUNC
	)

	file = IO.open(fd)
	yield file

	until in_sync
		# Clear out any extra zombie bits
		file.syswrite(?~.freeze)
		# Start the device
		file.syswrite(?#.freeze)
		file.flush

		sleep 0.125

		begin
			if file.read_nonblock(8000).include?(?~)
				in_sync = true
				break
			end
		rescue EOFError
			sleep 0.05
			retry
		end
	end

	sync_error_count = 0

	log 'success', 'Device ready!'
	file.read

	while true
		# cpu(01234) memUsed(999993) swapUsed(999992) io_active(0)
		# netUpload(999991) netDownload(999990)
		# disktotal(999990) diskused(999990)

		memstat = LS::Memory.stat
		_mem_u = memstat[:used].to_i.*(1024).*(100).fdiv(memstat[:total].to_i * 1024)
		mem_u = _mem_u.nan? ? 255 : _mem_u.round

		swapstat = LS::Swap.stat
		_swap_u = swapstat[:used].to_i.*(1024).*(100).fdiv(swapstat[:total].to_i * 1024)
		swap_u = _swap_u.nan? ? 255 : _swap_u.round

		time_minute = Time.now.min
		time_hour = Time.now.hour

		if (time_minute != prev_time[:min] || time_hour != prev_time[:hour]) && !latitude.nil? && !longitude.nil?
			dark_outside = DaylightChecker.new(
				latitude,
				longitude,
				Time.now
			).is_it_dark?

			built_in_led_state = dark_outside ? 1 : 0

			prev_time[:min] = time_minute
			prev_time[:hour] = time_hour
		end

		# Output has to be exactly this long. If not, blink-taskmanager shows invalid result.
		# No string is split inside blink-task manager, it just depends on the string length.
		#
		# cpu(100) memUsed(100) swapUsed(100)
		# netDownload(9991) netUpload(9991)
		# ioWrite(9991) ioRead(9991)

		# Debugging string
		# str = "#{"%03d" % cpu_u} #{"%03d" % mem_u} #{"%03d" % swap_u} "\
		# "#{convert_bytes(net_u)} #{convert_bytes(net_d)} "\
		# "#{convert_bytes(io_r)} #{convert_bytes(io_w)}"

		str = "!##{"%03d" % cpu_u}#{"%03d" % mem_u}#{"%03d" % swap_u}"\
		"#{convert_bytes(net_u)}#{convert_bytes(net_d)}"\
		"#{convert_bytes(io_r)}#{convert_bytes(io_w)}#{built_in_led_state}1~"

		# Rescuing from suspend
		file.syswrite(str)
		file.flush
		crc32 = file.read.scrub![/\d+/]

		unless crc32 == prev_crc32 || prev_crc32.empty?
			raise SyncError if sync_error_count > 1
			sync_error_count += 1
		else
			sync_error_count = 0 unless sync_error_count == 0
		end

		prev_crc32 = BlinkTM.crc32(str[2..-2])
		sleep REFRESH
	end

	unless device
		puts "#{BlinkTM::BOLD}#{BlinkTM::RED}:: #{Time.now.strftime('%H:%M:%S.%2N')}: Error establishing connection. Don't worry if this is a valid device. Retrying...#{BlinkTM::RESET}"
		sleep 0.1
	end
end