Class: RBZK::ZK

Inherits:
Object
  • Object
show all
Includes:
Constants
Defined in:
lib/rbzk/zk.rb

Constant Summary

Constants included from Constants

Constants::CMD_ACK_DATA, Constants::CMD_ACK_ERROR, Constants::CMD_ACK_ERROR_CMD, Constants::CMD_ACK_ERROR_DATA, Constants::CMD_ACK_ERROR_INIT, Constants::CMD_ACK_OK, Constants::CMD_ACK_REPEAT, Constants::CMD_ACK_RETRY, Constants::CMD_ACK_UNAUTH, Constants::CMD_ACK_UNKNOWN, Constants::CMD_ATTLOG_RRQ, Constants::CMD_AUTH, Constants::CMD_CANCELCAPTURE, Constants::CMD_CAPTUREFINGER, Constants::CMD_CAPTUREIMAGE, Constants::CMD_CHANGE_SPEED, Constants::CMD_CLEAR_ACC, Constants::CMD_CLEAR_ADMIN, Constants::CMD_CLEAR_ATTLOG, Constants::CMD_CLEAR_DATA, Constants::CMD_CLEAR_LCD, Constants::CMD_CLEAR_OPLOG, Constants::CMD_CONNECT, Constants::CMD_DATA, Constants::CMD_DB_RRQ, Constants::CMD_DELETE_SMS, Constants::CMD_DELETE_UDATA, Constants::CMD_DELETE_USER, Constants::CMD_DELETE_USERTEMP, Constants::CMD_DEL_USER_TEMP, Constants::CMD_DISABLEDEVICE, Constants::CMD_DOORSTATE_RRQ, Constants::CMD_EMPTY_MIFARE, Constants::CMD_ENABLEDEVICE, Constants::CMD_ENABLE_CLOCK, Constants::CMD_EXIT, Constants::CMD_FREE_DATA, Constants::CMD_GET_FREE_SIZES, Constants::CMD_GET_PINWIDTH, Constants::CMD_GET_TIME, Constants::CMD_GET_USERTEMP, Constants::CMD_GET_VERSION, Constants::CMD_GRPTZ_RRQ, Constants::CMD_GRPTZ_WRQ, Constants::CMD_OPLOG_RRQ, Constants::CMD_OPTIONS_RRQ, Constants::CMD_OPTIONS_WRQ, Constants::CMD_POWEROFF, Constants::CMD_PREPARE_BUFFER, Constants::CMD_PREPARE_DATA, Constants::CMD_READFILE_DATA, Constants::CMD_READ_BUFFER, Constants::CMD_REFRESHDATA, Constants::CMD_REFRESHOPTION, Constants::CMD_REG_EVENT, Constants::CMD_RESTART, Constants::CMD_RESUME, Constants::CMD_SAVE_USERTEMPS, Constants::CMD_SET_TIME, Constants::CMD_SLEEP, Constants::CMD_SMS_RRQ, Constants::CMD_SMS_WRQ, Constants::CMD_STARTENROLL, Constants::CMD_STARTVERIFY, Constants::CMD_STATE_RRQ, Constants::CMD_TESTVOICE, Constants::CMD_TEST_TEMP, Constants::CMD_TZ_RRQ, Constants::CMD_TZ_WRQ, Constants::CMD_UDATA_WRQ, Constants::CMD_ULG_RRQ, Constants::CMD_ULG_WRQ, Constants::CMD_UNLOCK, Constants::CMD_USERGRP_RRQ, Constants::CMD_USERGRP_WRQ, Constants::CMD_USERTEMP_RRQ, Constants::CMD_USERTEMP_WRQ, Constants::CMD_USERTZ_RRQ, Constants::CMD_USERTZ_WRQ, Constants::CMD_USER_WRQ, Constants::CMD_WRITE_LCD, Constants::CMD_WRITE_MIFARE, Constants::EF_ALARM, Constants::EF_ATTLOG, Constants::EF_BUTTON, Constants::EF_ENROLLFINGER, Constants::EF_ENROLLUSER, Constants::EF_FINGER, Constants::EF_FPFTR, Constants::EF_UNLOCK, Constants::EF_VERIFY, Constants::FCT_ATTLOG, Constants::FCT_FINGERTMP, Constants::FCT_OPLOG, Constants::FCT_SMS, Constants::FCT_UDATA, Constants::FCT_USER, Constants::FCT_WORKCODE, Constants::MACHINE_PREPARE_DATA_1, Constants::MACHINE_PREPARE_DATA_2, Constants::USER_ADMIN, Constants::USER_DEFAULT, Constants::USER_ENROLLER, Constants::USER_MANAGER, Constants::USHRT_MAX

Instance Method Summary collapse

Constructor Details

#initialize(ip, port: 4370, timeout: 60, password: 0, force_udp: false, omit_ping: false, verbose: false, encoding: 'UTF-8') ⇒ ZK



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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
# File 'lib/rbzk/zk.rb', line 54

def initialize(ip, port: 4370, timeout: 60, password: 0, force_udp: false, omit_ping: false, verbose: false,
               encoding: 'UTF-8')
  # Initialize the ZK device connection
  RBZK::User.encoding = encoding
  @address = [ ip, port ]

  @ip = ip
  @port = port
  @timeout = timeout
  @password = password
  @force_udp = force_udp
  @omit_ping = omit_ping
  @verbose = verbose
  @encoding = encoding

  @tcp = !force_udp
  @socket = nil

  # Initialize session variables
  @session_id = 0
  @reply_id = USHRT_MAX - 1
  @data_recv = nil
  @data = nil
  @connected = false
  @next_uid = 1
  @next_user_id = '1'
  @user_packet_size = 28

  # Storage for user and attendance data
  @users = {}
  @attendances = []
  @fingers = {}
  @tcp_header_size = 8

  # Initialize device info variables
  @users = 0
  @fingers = 0
  @records = 0
  @dummy = 0
  @cards = 0
  @fingers_cap = 0
  @users_cap = 0
  @rec_cap = 0
  @faces = 0
  @faces_cap = 0
  @fingers_av = 0
  @users_av = 0
  @rec_av = 0

  # Create helper for ping and TCP tests
  @helper = ZKHelper.new(ip, port)

  return unless @verbose

  puts "ZK instance created for device at #{@ip}:#{@port}"
  puts "Using #{@force_udp ? 'UDP' : 'TCP'} mode"
end

Instance Method Details

#clear_attendance_logsObject



1171
1172
1173
1174
1175
# File 'lib/rbzk/zk.rb', line 1171

def clear_attendance_logs
  send_command(CMD_CLEAR_ATTLOG)
  recv_reply
  true
end

#clear_dataObject



1177
1178
1179
1180
1181
# File 'lib/rbzk/zk.rb', line 1177

def clear_data
  send_command(CMD_CLEAR_DATA)
  recv_reply
  true
end

#clear_lcdBoolean

Clear LCD



383
384
385
386
387
388
389
# File 'lib/rbzk/zk.rb', line 383

def clear_lcd
  response = send_command(CMD_CLEAR_LCD)

  raise RBZK::ZKErrorResponse, "Can't clear lcd" unless response && response[:status]

  true
end

#compare_binary(binary_string, python_expected) ⇒ Object

Helper method to compare binary data between Python and Ruby



1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
# File 'lib/rbzk/zk.rb', line 1222

def compare_binary(binary_string, python_expected)
  ruby_formatted = format_as_python_bytes(binary_string)

  if @verbose
    puts "Ruby binary: #{ruby_formatted}"
    puts "Python expected: #{python_expected}"

    if ruby_formatted != python_expected
      puts 'DIFFERENCE DETECTED!'
      # Show byte-by-byte comparison
      ruby_bytes = binary_string.bytes
      # Parse Python bytes string (format: b'\x01\x02')
      python_bytes = []
      python_str = python_expected[2..-2] # Remove b'' wrapper
      i = 0
      while i < python_str.length
        if python_str[i] == '\\' && python_str[i + 1] == 'x'
          # Handle \xNN format
          hex_val = python_str[i + 2..i + 3]
          python_bytes << hex_val.to_i(16)
          i += 4
        elsif python_str[i] == '\\'
          # Handle escape sequences
          case python_str[i + 1]
          when 't'
            python_bytes << 9
          when 'n'
            python_bytes << 10
          when 'r'
            python_bytes << 13
          when '\\'
            python_bytes << 92
          when "'"
            python_bytes << 39
          end
          i += 2
        else
          # Regular character
          python_bytes << python_str[i].ord
          i += 1
        end
      end

      # Show differences
      puts 'Byte-by-byte comparison:'
      max_len = [ ruby_bytes.length, python_bytes.length ].max
      (0...max_len).each do |j|
        ruby_byte = j < ruby_bytes.length ? ruby_bytes[j] : nil
        python_byte = j < python_bytes.length ? python_bytes[j] : nil
        match = ruby_byte == python_byte ? '✓' : '✗'
        puts "  Byte #{j}: Ruby=#{if ruby_byte.nil?
                                    'nil'
                                  else
                                    "0x#{ruby_byte.to_s(16).rjust(2,
                                                                  '0')}"
                                  end}, Python=#{if python_byte.nil?
                                                   'nil'
                                                 else
                                                   "0x#{python_byte.to_s(16).rjust(
                                                     2, '0'
                                                   )}"
                                                 end} #{match}"
      end
    else
      puts 'Binary data matches exactly!'
    end
  end

  ruby_formatted == python_expected
end

#connectObject



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
# File 'lib/rbzk/zk.rb', line 112

def connect
  return self if @connected

  # Skip ping check if requested
  raise RBZK::ZKNetworkError, "Can't reach device (ping #{@ip})" if !@omit_ping && !@helper.test_ping

  # Set user packet size if TCP connection is available
  if !@force_udp && @helper.test_tcp.zero?
    @user_packet_size = 72 # Default for ZK8
  end

  create_socket

  # Reset session variables
  @session_id = 0
  @reply_id = USHRT_MAX - 1

  puts 'Sending connect command to device' if @verbose

  begin
    cmd_response = send_command(CMD_CONNECT)
    @session_id = @header[2]

    # Authenticate if needed
    if cmd_response[:code] == CMD_ACK_UNAUTH
      puts 'try auth' if @verbose

      command_string = make_commkey(@password, @session_id)
      cmd_response = send_command(CMD_AUTH, command_string)
    end

    # Check response status
    if cmd_response[:status]
      @connected = true
      self
    else
      raise RBZK::ZKErrorResponse, 'Unauthenticated' if cmd_response[:code] == CMD_ACK_UNAUTH

      puts "Connect error response: #{cmd_response[:code]}" if @verbose

      raise RBZK::ZKErrorResponse, "Invalid response: Can't connect"
    end
  rescue StandardError => e
    @connected = false
    puts "Connection error: #{e.message}" if @verbose
    raise e
  end
end

#connected?Boolean



161
162
163
# File 'lib/rbzk/zk.rb', line 161

def connected?
  @connected
end

#debug_python_binary(label, data) ⇒ Object

Helper method to debug binary data in Python format only



1297
1298
1299
# File 'lib/rbzk/zk.rb', line 1297

def debug_python_binary(label, data)
  puts "#{label}: #{format_as_python_bytes(data)}"
end

#decode_time(t) ⇒ Object



1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
# File 'lib/rbzk/zk.rb', line 1103

def decode_time(t)
  # Convert binary timestamp to integer
  t = t.unpack1('L<')

  # Extract time components
  second = t % 60
  t /= 60

  minute = t % 60
  t /= 60

  hour = t % 24
  t /= 24

  day = t % 31 + 1
  t /= 31

  month = t % 12 + 1
  t /= 12

  year = t + 2000

  # Create Time object
  Time.new(year, month, day, hour, minute, second)
end

#decode_timehex(timehex) ⇒ Object

Decode a timestamp in hex format (6 bytes) Match Python’s __decode_timehex method



1131
1132
1133
1134
1135
1136
1137
1138
# File 'lib/rbzk/zk.rb', line 1131

def decode_timehex(timehex)
  # Extract time components
  year, month, day, hour, minute, second = timehex.unpack('C6')
  year += 2000

  # Create Time object
  Time.new(year, month, day, hour, minute, second)
end

#delete_user(uid: 0) ⇒ Boolean

Delete user by uid



484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/rbzk/zk.rb', line 484

def delete_user(uid: 0)
  # Send command
  command_string = [ uid ].pack('S<')
  response = send_command(CMD_DELETE_USER, command_string)

  unless response && response[:status]
    raise RBZK::ZKErrorResponse, "Can't delete user. User not found or other error."
  end

  refresh_data
  # Update next_uid if necessary
  @next_uid = uid if uid == (@next_uid - 1)
  true
end

#disable_deviceObject



188
189
190
191
192
193
194
# File 'lib/rbzk/zk.rb', line 188

def disable_device
  cmd_response = send_command(CMD_DISABLEDEVICE)
  raise RBZK::ZKErrorResponse, "Can't disable device" unless cmd_response[:status]

  @is_enabled = false
  true
end

#disconnectObject



165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/rbzk/zk.rb', line 165

def disconnect
  return unless @connected

  send_command(CMD_EXIT)
  recv_reply

  @connected = false
  @socket&.close

  @socket = nil
  @tcp = nil

  true
end

#enable_deviceObject



180
181
182
183
184
185
186
# File 'lib/rbzk/zk.rb', line 180

def enable_device
  cmd_response = send_command(CMD_ENABLEDEVICE)
  raise RBZK::ZKErrorResponse, "Can't enable device" unless cmd_response && cmd_response[:status]

  @is_enabled = true
  true
end

#encode_time(t) ⇒ Object



1140
1141
1142
1143
1144
1145
1146
# File 'lib/rbzk/zk.rb', line 1140

def encode_time(t)
  # Calculate encoded timestamp
  (
    ((t.year % 100) * 12 * 31 + ((t.month - 1) * 31) + t.day - 1) *
      (24 * 60 * 60) + (t.hour * 60 + t.minute) * 60 + t.second
  )
end

#format_as_python_bytes(binary_string) ⇒ Object Also known as: python_format

Helper method to print binary data in Python format



1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
# File 'lib/rbzk/zk.rb', line 1184

def format_as_python_bytes(binary_string)
  return "b''" if binary_string.nil? || binary_string.empty?

  result = "b'"
  binary_string.each_byte do |byte|
    result += case byte
              when 0x0d # Carriage return - Python shows as \r
                '\\r'
              when 0x0a # Line feed - Python shows as \n
                '\\n'
              when 0x09 # Tab - Python shows as \t
                '\\t'
              when 0x07 # Bell - Python can show as \a or \x07
                '\\x07'
              when 0x08 # Backspace - Python shows as \b
                '\\b'
              when 0x0c # Form feed - Python shows as \f
                '\\f'
              when 0x0b # Vertical tab - Python shows as \v
                '\\v'
              when 0x5c # Backslash - Python shows as \\
                '\\\\'
              when 0x27 # Single quote - Python shows as \'
                "\\'"
              when 0x22 # Double quote - Python shows as \"
                '\"'
              when 32..126 # Printable ASCII
                byte.chr
              else
                # All other bytes - Python shows as \xHH
                "\\x#{byte.to_s(16).rjust(2, '0')}"
              end
  end
  result += "'"
  result
end

#free_dataObject

Helper method to clear buffer (like Python’s free_data)



807
808
809
810
811
812
813
814
# File 'lib/rbzk/zk.rb', line 807

def free_data
  command = CMD_FREE_DATA
  response = send_command(command)

  raise RBZK::ZKErrorResponse, "Can't free data" unless response && response[:status]

  true
end

#get_attendance_logsObject



970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
# File 'lib/rbzk/zk.rb', line 970

def get_attendance_logs
  # First, read device sizes to get record count
  read_sizes

  # If no records, return empty array
  return [] if @records.zero?

  # Get users for lookup
  users = get_users

  puts "Found #{users.size} users" if @verbose

  logs = []

  # Read attendance data with buffer
  attendance_data, size = read_with_buffer(CMD_ATTLOG_RRQ)

  if size < 4
    puts 'WRN: no attendance data' if @verbose
    return []
  end

  # Get total size from first 4 bytes
  total_size = attendance_data[0...4].unpack1('I')

  # Calculate record size
  record_size = @records.positive? ? total_size / @records : 0

  puts "record_size is #{record_size}" if @verbose

  # Remove the first 4 bytes (total size)
  attendance_data = attendance_data[4..-1]

  if record_size == 8
    # Handle 8-byte records
    while attendance_data && attendance_data.size >= 8
      # In Python: uid, status, timestamp, punch = unpack('HB4sB', attendance_data.ljust(8, b'\x00')[:8])
      uid, status, timestamp_raw, punch = attendance_data[0...8].ljust(8, "\x00".b).unpack('S<C4sC')

      if @verbose
        puts "Attendance data (hex): #{attendance_data[0...8].bytes.map do |b|
          "0x#{b.to_s(16).rjust(2, '0')}"
        end.join(' ')}"
      end

      attendance_data = attendance_data[8..-1]

      # Look up user by uid
      tuser = users.find { |u| u.uid == uid }
      user_id = if !tuser
                  uid.to_s
                else
                  tuser.user_id
                end

      # Decode timestamp
      timestamp = decode_time(timestamp_raw)

      # Create attendance record
      attendance = RBZK::Attendance.new(user_id, timestamp, status, punch, uid)
      logs << attendance
    end
  elsif record_size == 16
    # Handle 16-byte records
    while attendance_data && attendance_data.size >= 16
      # In Python: user_id, timestamp, status, punch, reserved, workcode = unpack('<I4sBB2sI', attendance_data.ljust(16, b'\x00')[:16])
      user_id_raw, timestamp_raw, status, punch, _reserved, _workcode = attendance_data[0...16].ljust(16,
                                                                                                      "\x00".b).unpack('L<4sCCa2L<')

      if @verbose
        puts "Attendance data (hex): #{attendance_data[0...16].bytes.map do |b|
          "0x#{b.to_s(16).rjust(2, '0')}"
        end.join(' ')}"
      end

      attendance_data = attendance_data[16..-1]

      # Convert user_id to string
      user_id = user_id_raw.to_s

      # Look up user by user_id and uid
      tuser = users.find { |u| u.user_id == user_id }
      if !tuser
        puts "no uid #{user_id}" if @verbose
        uid = user_id
        tuser = users.find { |u| u.uid.to_s == user_id }
        if !tuser
          uid = user_id
        else
          uid = tuser.uid
          user_id = tuser.user_id
        end
      else
        uid = tuser.uid
      end

      # Decode timestamp
      timestamp = decode_time(timestamp_raw)

      # Create attendance record
      attendance = RBZK::Attendance.new(user_id, timestamp, status, punch, uid)
      logs << attendance
    end
  else
    # Handle 40-byte records (default)
    while attendance_data && attendance_data.size >= 40
      # In Python: uid, user_id, status, timestamp, punch, space = unpack('<H24sB4sB8s', attendance_data.ljust(40, b'\x00')[:40])
      uid, user_id_raw, status, timestamp_raw, punch, _space = attendance_data[0...40].ljust(40,
                                                                                             "\x00".b).unpack('S<a24Ca4Ca8')

      if @verbose
        puts "Attendance data (hex): #{attendance_data[0...40].bytes.map do |b|
          "0x#{b.to_s(16).rjust(2, '0')}"
        end.join(' ')}"
      end

      # Extract user_id from null-terminated string
      user_id = user_id_raw.split("\x00")[0].to_s

      # Decode timestamp
      timestamp = decode_time(timestamp_raw)

      # Create attendance record
      attendance = RBZK::Attendance.new(user_id, timestamp, status, punch, uid)
      logs << attendance

      attendance_data = attendance_data[record_size..-1]
    end
  end

  logs
end

#get_data_sizeObject

Helper method to get data size from the current data



594
595
596
597
598
599
600
601
# File 'lib/rbzk/zk.rb', line 594

def get_data_size
  if @data && @data.size >= 4
    @data[0...4].unpack1('L<')

  else
    0
  end
end

#get_device_nameObject



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'lib/rbzk/zk.rb', line 235

def get_device_name
  command = CMD_OPTIONS_RRQ
  command_string = "~DeviceName\x00".b
  response_size = 1024

  response = send_command(command, command_string, response_size)

  if response && response[:status]
    device_field = @data.split('=', 2)[1]
    device = device_field ? device_field.split("\x00")[0] : ''
    device.to_s
  else
    ''
  end
end

#get_extend_fmtObject



269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/rbzk/zk.rb', line 269

def get_extend_fmt
  command = CMD_OPTIONS_RRQ
  command_string = "~ExtendFmt\x00".b
  response_size = 1024

  response = send_command(command, command_string, response_size)

  return unless response && response[:status]

  fmt_field = @data.split('=', 2)[1]
  fmt = fmt_field ? fmt_field.split("\x00")[0] : ''
  begin
    fmt.to_i
  rescue StandardError
    0
  end
end

#get_face_versionObject



251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'lib/rbzk/zk.rb', line 251

def get_face_version
  command = CMD_OPTIONS_RRQ
  command_string = "ZKFaceVersion\x00".b
  response_size = 1024

  response = send_command(command, command_string, response_size)

  return unless response && response[:status]

  version_field = @data.split('=', 2)[1]
  version = version_field ? version_field.split("\x00")[0] : ''
  begin
    version.to_i
  rescue StandardError
    0
  end
end

#get_firmware_versionObject



196
197
198
199
200
201
202
203
204
205
# File 'lib/rbzk/zk.rb', line 196

def get_firmware_version
  command = CMD_GET_VERSION
  response_size = 1024
  response = send_command(command, '', response_size)

  raise RBZK::ZKErrorResponse, "Can't read firmware version" unless response && response[:status]

  firmware_version = @data.split("\x00")[0]
  firmware_version.to_s
end

#get_fp_versionObject



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# File 'lib/rbzk/zk.rb', line 302

def get_fp_version
  command = CMD_OPTIONS_RRQ
  command_string = "~ZKFPVersion\x00".b
  response_size = 1024

  response = send_command(command, command_string, response_size)

  raise RBZK::ZKErrorResponse, "Can't read fingerprint version" unless response && response[:status]

  version_field = @data.split('=', 2)[1]
  version = version_field ? version_field.split("\x00")[0] : ''
  version = version.gsub('=', '')
  begin
    version.to_i
  rescue StandardError
    0
  end
end

#get_free_sizesObject



1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
# File 'lib/rbzk/zk.rb', line 1357

def get_free_sizes
  send_command(CMD_GET_FREE_SIZES)
  reply = recv_reply

  if reply && reply.size >= 8
    sizes_data = reply[8..-1].unpack('S<*')

    return {
      users: sizes_data[0],
      fingers: sizes_data[2],
      capacity: sizes_data[4],
      logs: sizes_data[6],
      passwords: sizes_data[8]
    }
  end

  nil
end

#get_lock_stateBoolean

Get the lock state



358
359
360
361
362
363
364
365
366
# File 'lib/rbzk/zk.rb', line 358

def get_lock_state
  response = send_command(CMD_DOORSTATE_RRQ)

  if response && response[:status]
    true
  else
    false
  end
end

#get_macObject



222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/rbzk/zk.rb', line 222

def get_mac
  command = CMD_OPTIONS_RRQ
  command_string = "MAC\x00".b
  response_size = 1024

  response = send_command(command, command_string, response_size)

  raise RBZK::ZKErrorResponse, "Can't read MAC address" unless response && response[:status]

  mac = @data.split('=', 2)[1]&.split("\x00")&.[](0) || ''
  mac.to_s
end

#get_platformObject



287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/rbzk/zk.rb', line 287

def get_platform
  command = CMD_OPTIONS_RRQ
  command_string = "~Platform\x00".b
  response_size = 1024

  response = send_command(command, command_string, response_size)

  raise RBZK::ZKErrorResponse, "Can't read platform name" unless response && response[:status]

  platform_field = @data.split('=', 2)[1]
  platform = platform_field ? platform_field.split("\x00")[0] : ''
  platform = platform.gsub('=', '')
  platform.to_s
end

#get_serialnumberObject



207
208
209
210
211
212
213
214
215
216
217
218
219
220
# File 'lib/rbzk/zk.rb', line 207

def get_serialnumber
  command = CMD_OPTIONS_RRQ
  command_string = "~SerialNumber\x00".b
  response_size = 1024

  response = send_command(command, command_string, response_size)

  raise RBZK::ZKErrorResponse, "Can't read serial number" unless response && response[:status]

  serialnumber_field = @data.split('=', 2)[1]
  serialnumber = serialnumber_field ? serialnumber_field.split("\x00")[0] : ''
  serialnumber = serialnumber.gsub('=', '')
  serialnumber.to_s
end

#get_templatesObject



1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
# File 'lib/rbzk/zk.rb', line 1376

def get_templates
  fingers = []

  send_command(CMD_PREPARE_DATA, [ FCT_FINGERTMP ].pack('C'))
  recv_reply

  data_size = recv_long
  templates_data = recv_chunk(data_size)

  if templates_data && !templates_data.empty?
    offset = 0
    while offset < data_size
      if data_size - offset >= 608
        template_data = templates_data[offset..offset + 608]
        uid, fid, valid, template = template_data.unpack('S<S<C a*')

        fingers << RBZK::Finger.new(uid, fid, valid, template)
      end

      offset += 608
    end
  end

  fingers
end

#get_timeObject



1148
1149
1150
1151
1152
1153
1154
1155
1156
# File 'lib/rbzk/zk.rb', line 1148

def get_time
  command = CMD_GET_TIME
  response_size = 1032
  response = send_command(command, '', response_size)

  raise RBZK::ZKErrorResponse, "Can't get time" unless response && response[:status]

  decode_time(@data[0...4])
end

#get_user_template(uid, finger_id) ⇒ Object



1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
# File 'lib/rbzk/zk.rb', line 1402

def get_user_template(uid, finger_id)
  send_command(CMD_GET_USERTEMP, [ uid, finger_id ].pack('S<S<'))
  reply = recv_reply

  if reply && reply.size >= 8
    template_data = reply[8..-1]
    valid = template_data[0].ord
    template = template_data[1..-1]

    return RBZK::Finger.new(uid, finger_id, valid, template)
  end

  nil
end

#get_usersObject



893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
# File 'lib/rbzk/zk.rb', line 893

def get_users
  # Read sizes
  read_sizes

  puts "Device has #{@users} users" if @verbose

  # If no users, return empty array
  if @users.zero?
    @next_uid = 1
    @next_user_id = '1'
    return []
  end

  users = []
  max_uid = 0
  userdata, size = read_with_buffer(CMD_USERTEMP_RRQ, FCT_USER)
  puts "user size #{size} (= #{userdata.length})" if @verbose

  if size <= 4
    puts 'WRN: missing user data'
    return []
  end

  total_size = userdata[0, 4].unpack1('L<')
  @user_packet_size = total_size / @users

  puts "WRN packet size would be #{@user_packet_size}" if ![ 28, 72 ].include?(@user_packet_size) && @verbose

  userdata = userdata[4..-1]

  if @user_packet_size == 28
    while userdata.length >= 28
      uid, privilege, password, name, card, group_id, timezone, user_id = userdata.ljust(28, "\x00")[0,
                                                                                                     28].unpack('S<Ca5a8L<xCs<L<')
      max_uid = uid if uid > max_uid
      password = password.split("\x00").first&.force_encoding(@encoding)&.encode('UTF-8', invalid: :replace)
      name = name.split("\x00").first&.force_encoding(@encoding)&.encode('UTF-8', invalid: :replace)&.strip
      group_id = group_id.to_s
      user_id = user_id.to_s
      name ||= "NN-#{user_id}"
      user = User.new(uid, name, privilege, password, group_id, user_id, card)
      users << user
      if @verbose
        puts "[6]user: #{uid}, #{privilege}, #{password}, #{name}, #{card}, #{group_id}, #{timezone}, #{user_id}"
      end
      userdata = userdata[28..-1]
    end
  else
    while userdata.length >= 72
      uid, privilege, password, name, card, group_id, user_id = userdata.ljust(72, "\x00")[0,
                                                                                           72].unpack('S<Ca8a24L<xa7xa24')
      max_uid = uid if uid > max_uid
      password = password.split("\x00").first&.force_encoding(@encoding)&.encode('UTF-8', invalid: :replace)
      name = name.split("\x00").first&.force_encoding(@encoding)&.encode('UTF-8', invalid: :replace)&.strip
      group_id = group_id.split("\x00").first&.force_encoding(@encoding)&.encode('UTF-8', invalid: :replace)&.strip
      user_id = user_id.split("\x00").first&.force_encoding(@encoding)&.encode('UTF-8', invalid: :replace)
      name ||= "NN-#{user_id}"
      user = User.new(uid, name, privilege, password, group_id, user_id, card)
      users << user
      userdata = userdata[72..-1]
    end
  end

  max_uid += 1
  @next_uid = max_uid
  @next_user_id = max_uid.to_s

  loop do
    break unless users.any? { |u| u.user_id == @next_user_id }

    max_uid += 1
    @next_user_id = max_uid.to_s
  end

  users
end

#poweroffObject



327
328
329
330
331
# File 'lib/rbzk/zk.rb', line 327

def poweroff
  send_command(CMD_POWEROFF)
  recv_reply
  true
end

#read_chunk(start, size) ⇒ Object

Helper method to read a chunk of data



857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
# File 'lib/rbzk/zk.rb', line 857

def read_chunk(start, size)
  puts "Reading chunk: start=#{start}, size=#{size}" if @verbose

  3.times do |attempt|
    # In Python: command = const._CMD_READ_BUFFER (which is 1504)
    # In Ruby, we should use CMD_READ_BUFFER (1504) instead of CMD_READFILE_DATA (81)
    command = 1504 # CMD_READ_BUFFER

    # In Python: command_string = pack('<ii', start, size)
    command_string = [ start, size ].pack('l<l<')

    # In Python: response_size = size + 32 if self.tcp else 1024 + 8
    response_size = @tcp ? size + 32 : 1024 + 8

    # In Python: cmd_response = self.__send_command(command, command_string, response_size)
    response = send_command(command, command_string, response_size)

    if !response || !response[:status]
      puts "Failed to read chunk on attempt #{attempt + 1}" if @verbose
      next
    end

    # In Python: data = self.__recieve_chunk()
    data = receive_chunk

    next unless data

    puts "Received chunk of #{data.size} bytes" if @verbose

    return data
  end

  # If we get here, all retries failed
  raise RBZK::ZKErrorResponse, "can't read chunk #{start}:[#{size}]"
end

#read_sizesObject



1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
# File 'lib/rbzk/zk.rb', line 1301

def read_sizes
  command = CMD_GET_FREE_SIZES
  response_size = 1024
  cmd_response = send_command(command, '', response_size)

  raise RBZK::ZKErrorResponse, "Can't read sizes" unless cmd_response && cmd_response[:status]

  if @verbose
    puts "Data hex: #{@data.bytes.map { |b| "0x#{b.to_s(16).rjust(2, '0')}" }.join(' ')}"
    puts "Data Python format: #{python_format(@data)}"
  end

  size = @data.size
  puts "Data size: #{size} bytes" if @verbose

  if @data.size >= 80
    # In Python: fields = unpack('20i', self.__data[:80])
    # In Ruby, 'l<' is a signed 32-bit integer (4 bytes) in little-endian format, which matches Python's 'i'
    fields = @data[0...80].unpack('l<20')

    puts "Unpacked fields: #{fields.inspect}" if @verbose

    @users = fields[4]
    @fingers = fields[6]
    @records = fields[8]
    @dummy = fields[10] # ???
    @cards = fields[12]
    @fingers_cap = fields[14]
    @users_cap = fields[15]
    @rec_cap = fields[16]
    @fingers_av = fields[17]
    @users_av = fields[18]
    @rec_av = fields[19]
    @data = @data[80..-1]

    # Check for face information (added to match Python implementation)
    if @data.size >= 12 # face info
      # In Python: fields = unpack('3i', self.__data[:12]) #dirty hack! we need more information
      face_fields = @data[0...12].unpack('l<3')
      @faces = face_fields[0]
      @faces_cap = face_fields[2]

      puts "Face info: faces=#{@faces}, capacity=#{@faces_cap}" if @verbose
    end

    if @verbose
      puts "Device info: users=#{@users}, fingers=#{@fingers}, records=#{@records}"
      puts "Capacity: users=#{@users_cap}, fingers=#{@fingers_cap}, records=#{@rec_cap}"
    end

    return true
  end

  false
end

#read_with_buffer(command, fct = 0, ext = 0) ⇒ Object

Helper method to read data with buffer (ZK6: 1503)



500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
# File 'lib/rbzk/zk.rb', line 500

def read_with_buffer(command, fct = 0, ext = 0)
  puts "Reading data with buffer: command=#{command}, fct=#{fct}, ext=#{ext}" if @verbose

  # Set max chunk size based on connection type
  max_chunk = @tcp ? 0xFFc0 : 16 * 1024

  # Pack the command parameters into a binary string
  # Format: 1 byte signed char, 2 byte short, 4 byte long, 4 byte long
  # All in little-endian format
  command_string = [ 1, command, fct, ext ].pack('cs<l<l<')

  puts "Command string: #{python_format(command_string)}" if @verbose

  # Send the command to prepare the buffer
  response_size = 1024
  # local variables
  response = send_command(CMD_PREPARE_BUFFER, command_string, response_size)

  raise RBZK::ZKErrorResponse, 'Read with buffer not supported' if !response || !response[:status]

  # Get data from the response
  data = @data

  puts "Received #{data.size} bytes of data" if @verbose

  # Check if we need more data
  if response[:code] == CMD_DATA
    if @tcp
      puts "DATA! is #{data.size} bytes, tcp length is #{@tcp_length}" if @verbose

      if data.size < (@tcp_length - 8)
        need = (@tcp_length - 8) - data.size
        puts "need more data: #{need}" if @verbose

        # Receive more data to complete the buffer
        more_data = receive_raw_data(need)

        puts "Read #{more_data.size} more bytes" if @verbose

        # Combine the data
        result = data + more_data
        return result, data.size + more_data.size
      else
        puts 'Enough data' if @verbose
        size = data.size
        return data, size
      end
    else
      size = data.size
      return data, size
    end
  end

  # Get the size from the first 4 bytes (unsigned long, little-endian)
  size = data[1..4].unpack1('L<')

  puts "size fill be #{size}" if @verbose

  # Calculate chunks
  remain = size % max_chunk
  # Calculate number of full-sized packets (integer division)
  packets = (size - remain).div(max_chunk)

  puts "rwb: ##{packets} packets of max #{max_chunk} bytes, and extra #{remain} bytes remain" if @verbose

  # Read chunks
  result_data = []
  start = 0

  packets.times do
    puts "recieve chunk: prepare data size is #{max_chunk}" if @verbose
    chunk = read_chunk(start, max_chunk)
    result_data << chunk
    start += max_chunk
  end

  if remain.positive?
    puts "recieve chunk: prepare data size is #{remain}" if @verbose
    chunk = read_chunk(start, remain)
    result_data << chunk
    start += remain
  end

  # Free data (equivalent to Python's self.free_data())
  free_data

  puts "_read w/chunk #{start} bytes" if @verbose

  # In Python: return b''.join(data), start
  result = result_data.join
  [ result, start ]
end

#receive_chunkObject

Helper method to receive a chunk (like Python’s __recieve_chunk)



682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
# File 'lib/rbzk/zk.rb', line 682

def receive_chunk
  if @response == CMD_DATA
    if @tcp
      puts "_rc_DATA! is #{@data.size} bytes, tcp length is #{@tcp_length}" if @verbose

      if @data.size < (@tcp_length - 8)
        need = (@tcp_length - 8) - @data.size
        puts "need more data: #{need}" if @verbose
        more_data = receive_raw_data(need)
        @data + more_data
      else
        puts 'Enough data' if @verbose
        @data
      end
    else
      puts "_rc len is #{@data.size}" if @verbose
      @data
    end
  elsif @response == CMD_PREPARE_DATA
    data = []
    size = get_data_size

    puts "recieve chunk: prepare data size is #{size}" if @verbose

    if @tcp
      if @data.size >= (8 + size)
        data_recv = @data[8..-1]
      else
        # [80, 80, 130, 125, 92, 7, 0, 0, 221, 5, 142, 172, 0, 0, 4, 0, 80, 7, 0, 0, 1, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 65, 98, 100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 2, 0, 14, 0, 0, 0, 0, 0, 0, 0, 0, 65, 110, 97, 115, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 50, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 111, 110, 100, 111, 115, 44, 65, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 51, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 116, 97, 0, 111, 115, 44, 65, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 52, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 97, 121, 115, 0, 115, 44, 65, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 53, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 82, 97, 119, 97, 110, 0, 44, 65, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 54, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 74, 101, 110, 97, 110, 0, 44, 65, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 55, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 70, 97, 114, 97, 104, 0, 44, 65, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 56, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 97, 98, 114, 101, 101, 110, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 57, 0, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 97, 101, 101, 100, 0, 110, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 48, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 71, 111, 102, 114, 97, 110, 0, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 49, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 68, 97, 110, 105, 97, 0, 0, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 50, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 97, 109, 105, 97, 0, 0, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 51, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 14, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 82, 101, 101, 109, 0, 0, 0, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 52, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 87, 97, 108, 97, 97, 0, 0, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 53, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 82, 97, 110, 101, 101, 109, 0, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 54, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 17, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 79, 108, 97, 0, 101, 109, 0, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 55, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 97, 114, 97, 104, 0, 0, 0, 98, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 56, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 19, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 111, 110, 100, 111, 115, 72, 65, 0, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 57, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 111, 0, 100, 111, 115, 72, 65, 0, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 52, 53, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 21, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 119, 115, 0, 111, 115, 72, 65, 0, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 49, 52, 54, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 22, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 97, 109, 97, 114, 97, 0, 65, 0, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 52, 53, 50, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 23, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 84, 97, 115, 110, 101, 101, 109, 0, 0, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 50, 48, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 69, 115, 114, 97, 97, 0, 109, 0, 0, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 50, 49, 0, 0, 1, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 83, 97, 114, 97, 106, 0, 109, 0, 0, 117, 107, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 50, 49, 51, 53, 0, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 26, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 108, 97, 97, 110, 97, 115, 115, 101, 114, 0, 104, 100, 97, 105, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 50, 50, 0, 53, 0, 0, 0, 0, 25, 0, 0, 0, 0, 254, 6, 119, 255, 255, 255, 255, 212, 10, 159, 127, 80, 80, 130, 125, 8, 0, 0, 0, 208, 7, 73, 81, 226, 166, 4, 0]
        data_recv = @data[8..-1] + @socket.recv(size + 32)
      end

      puts "data_recv: #{python_format(data_recv)}" if @verbose

      # hault_for_debuggg_DO_NOT_REMOVE
      resp, broken_header = receive_tcp_data(data_recv, size)
      data << resp if resp

      # get CMD_ACK_OK
      data_recv = if broken_header.size < 16
                    broken_header + @socket.recv(16)
                  else
                    broken_header
                  end

      if data_recv.size < 16
        puts "trying to complete broken ACK #{data_recv.size} /16"
        puts "data_recv: #{data_recv.bytes.map { |b| "0x#{b.to_s(16).rjust(2, '0')}" }.join(' ')}" if @verbose
        data_recv += @socket.recv(16 - data_recv.size) # TODO: CHECK HERE_!
      end

      unless test_tcp_top(data_recv)
        puts 'invalid chunk tcp ACK OK' if @verbose
        return nil
      end

      # In Python: response = unpack('HHHH', data_recv[8:16])[0]
      # This unpacks 4 shorts (8 bytes) but only uses the first one
      # In Ruby, we need to use 'S<4' to unpack 4 shorts in little-endian format
      response = data_recv[8...16].unpack1('S<4')

      if response == CMD_ACK_OK
        puts 'chunk tcp ACK OK!' if @verbose
        return data.join
      end

      if @verbose
        puts "bad response #{format_as_python_bytes(data_recv)}"
        puts "data: #{data.map { |d| format_as_python_bytes(d) }.join(', ')}"
      end

      nil
    else
      # Non-TCP implementation
      loop do
        data_recv = @socket.recv(1024 + 8)
        response = data_recv[0...8].unpack1('S<S<S<S<')

        puts "# packet response is: #{response}" if @verbose

        if response == CMD_DATA
          data << data_recv[8..-1]
          size -= 1024
        elsif response == CMD_ACK_OK
          break
        else
          puts 'broken!' if @verbose
          break
        end

        puts "still needs #{size}" if @verbose
      end

      data.join
    end
  else
    puts "invalid response #{@response}" if @verbose
    nil
  end
end

#receive_raw_data(size) ⇒ Object

Helper method to receive raw data (like Python’s __recieve_raw_data)



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
# File 'lib/rbzk/zk.rb', line 784

def receive_raw_data(size)
  data = []
  puts "expecting #{size} bytes raw data" if @verbose

  while size.positive?
    data_recv = @socket.recv(size)
    received = data_recv.size

    if @verbose
      puts "partial recv #{received}"
      puts "   recv #{data_recv.bytes.map { |b| "0x#{b.to_s(16).rjust(2, '0')}" }.join(' ')}" if received < 100
    end

    data << data_recv
    size -= received

    puts "still need #{size}" if @verbose
  end

  data.join
end

#receive_tcp_data(data_recv, size) ⇒ Object

Helper method to receive TCP data



604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# File 'lib/rbzk/zk.rb', line 604

def receive_tcp_data(data_recv, size)
  data = []
  tcp_length = test_tcp_top(data_recv)

  puts "tcp_length #{tcp_length}, size #{size}" if @verbose

  if tcp_length <= 0
    puts 'Incorrect tcp packet' if @verbose
    return nil, ''.b
  end

  if (tcp_length - 8) < size
    puts 'tcp length too small... retrying' if @verbose

    # Recursive call to handle smaller packet
    resp, bh = receive_tcp_data(data_recv, tcp_length - 8)
    data << resp if resp
    size -= resp.size

    puts "new tcp DATA packet to fill misssing #{size}" if @verbose

    # Get more data to fill missing
    data_recv = bh + @socket.recv(size + 16)

    puts "new tcp DATA starting with #{data_recv.size} bytes" if @verbose

    # Another recursive call with new data
    resp, bh = receive_tcp_data(data_recv, size)
    data << resp

    puts "for misssing #{size} recieved #{resp ? resp.size : 0} with extra #{bh.size}" if @verbose

    return data.join, bh
  end

  received = data_recv.size

  puts "received #{received}, size #{size}" if @verbose

  # In Python: response = unpack('HHHH', data_recv[8:16])[0]
  # This unpacks 4 shorts (8 bytes) but only uses the first one
  response = data_recv[8...16].unpack1('S<S<S<S<')

  if received >= (size + 32)
    if response == CMD_DATA
      resp = data_recv[16...(size + 16)]

      puts "resp complete len #{resp.size}" if @verbose

      [ resp, data_recv[(size + 16)..-1] ]
    else
      puts "incorrect response!!! #{response}" if @verbose

      [ nil, ''.b ]
    end
  else
    puts "try DATA incomplete (actual valid #{received - 16})" if @verbose

    data << data_recv[16...(size + 16)]
    size -= received - 16
    broken_header = ''.b

    if size.negative?
      broken_header = data_recv[size..-1]

      puts "broken: #{broken_header.bytes.map { |b| format('%02x', b) }.join}" if @verbose
    end

    if size.positive?
      data_recv = receive_raw_data(size)
      data << data_recv
    end

    [ data.join, broken_header ]
  end
end

#refresh_dataBoolean

Refresh the device data



393
394
395
396
397
398
399
# File 'lib/rbzk/zk.rb', line 393

def refresh_data
  response = send_command(CMD_REFRESHDATA)

  raise RBZK::ZKErrorResponse, "Can't refresh data" unless response && response[:status]

  true
end

#restartObject



321
322
323
324
325
# File 'lib/rbzk/zk.rb', line 321

def restart
  send_command(CMD_RESTART)
  recv_reply
  true
end

#send_chunk(command_string) ⇒ Boolean

Send a chunk of data



847
848
849
850
851
852
853
854
# File 'lib/rbzk/zk.rb', line 847

def send_chunk(command_string)
  command = CMD_DATA
  response = send_command(command, command_string)

  raise RBZK::ZKErrorResponse, "Can't send chunk" unless response && response[:status]

  true
end

#send_with_buffer(buffer) ⇒ Boolean

Send data with buffer



819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
# File 'lib/rbzk/zk.rb', line 819

def send_with_buffer(buffer)
  max_chunk = 1024
  size = buffer.size
  free_data

  command = CMD_PREPARE_DATA
  command_string = [ size ].pack('L<')
  response = send_command(command, command_string)

  raise RBZK::ZKErrorResponse, "Can't prepare data" if !response || !response[:status]

  remain = size % max_chunk
  packets = (size - remain) / max_chunk
  start = 0

  packets.times do
    send_chunk(buffer[start, max_chunk])
    start += max_chunk
  end

  send_chunk(buffer[start, remain]) if remain.positive?

  true
end

#set_time(timestamp = nil) ⇒ Object



1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
# File 'lib/rbzk/zk.rb', line 1158

def set_time(timestamp = nil)
  # Default to current time if not provided
  timestamp ||= Time.now

  command = CMD_SET_TIME
  command_string = [ encode_time(timestamp) ].pack('L<')
  response = send_command(command, command_string)

  raise RBZK::ZKErrorResponse, "Can't set time" unless response && response[:status]

  true
end

#set_user(uid: nil, name: '', privilege: 0, password: '', group_id: '', user_id: '', card: 0) ⇒ Boolean

Create or update user by uid



410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/rbzk/zk.rb', line 410

def set_user(uid: nil, name: '', privilege: 0, password: '', group_id: '', user_id: '', card: 0)
  if uid.nil?
    ensure_user_metadata!
    uid = @next_uid
    user_id = @next_user_id if user_id.empty? && @next_user_id
  end

  # If uid is not provided, use next_uid
  user_id = uid.to_s if user_id.nil? || user_id.empty? # ZK6 needs uid2 == uid

  # Validate privilege
  privilege = USER_DEFAULT if privilege != USER_DEFAULT && privilege != USER_ADMIN
  privilege = privilege.to_i

  # Create command string based on user_packet_size
  if @user_packet_size == 28 # firmware == 6
    group_id = 0 if group_id.empty?

    begin
      command_string = [ uid, privilege ].pack('S<C') +
                       password.encode(@encoding, invalid: :replace, undef: :replace).ljust(5, "\x00")[0...5] +
                       name.encode(@encoding, invalid: :replace, undef: :replace).ljust(8, "\x00")[0...8] +
                       [ card.to_i, 0, group_id.to_i, 0, user_id.to_i ].pack('L<CS<S<L<')
    rescue StandardError => e
      puts "Error packing user: #{e.message}" if @verbose
      raise RBZK::ZKErrorResponse, "Can't pack user"
    end
  else
    # For other firmware versions
    name_pad = name.encode(@encoding, invalid: :replace, undef: :replace).ljust(24, "\x00")[0...24]
    card_str = [ card.to_i ].pack('L<')[0...4]
    command_string = "#{[ uid,
                          privilege ].pack('S<C')}#{password.encode(@encoding, invalid: :replace, undef: :replace).ljust(8,
                                                                                                                         "\x00")[0...8]}#{name_pad}#{card_str}\u0000#{group_id.encode(@encoding, invalid: :replace, undef: :replace).ljust(7,
                                                                                                                                                                                                                                           "\x00")[0...7]}\u0000#{user_id.encode(@encoding, invalid: :replace, undef: :replace).ljust(
                                                                                                                                                                                                                                             24, "\x00"
                                                                                                                                                                                                                                           )[0...24]}"
  end

  # Send command
  response = send_command(CMD_USER_WRQ, command_string, 1024)

  if response && response[:status]
    # Update next_uid and next_user_id if necessary
    refresh_data
    @next_uid += 1 if @next_uid == uid
    @next_user_id = @next_uid.to_s if @next_user_id == user_id
    true
  else
    code = response[:code] if response
    data_msg = @data && !@data.empty? ? " Data: #{format_as_python_bytes(@data)}" : ''
    raise RBZK::ZKErrorResponse, "Can't set user (device response: #{code || 'NO_CODE'})#{data_msg}"
  end
end

#test_voice(index = 0) ⇒ Object



333
334
335
336
337
338
339
340
341
342
# File 'lib/rbzk/zk.rb', line 333

def test_voice(index = 0)
  command_string = [ index ].pack('L<')
  response = send_command(CMD_TESTVOICE, command_string)

  if response && response[:status]
    true
  else
    false
  end
end

#unlock(time = 3) ⇒ Boolean

Unlock the door



347
348
349
350
351
352
353
354
# File 'lib/rbzk/zk.rb', line 347

def unlock(time = 3)
  command_string = [ time * 10 ].pack('L<')
  response = send_command(CMD_UNLOCK, command_string)

  raise RBZK::ZKErrorResponse, "Can't open door" unless response && response[:status]

  true
end

#write_lcd(line_number, text) ⇒ Boolean

Write text to LCD



372
373
374
375
376
377
378
379
# File 'lib/rbzk/zk.rb', line 372

def write_lcd(line_number, text)
  command_string = "#{[ line_number, 0 ].pack('s<c')} #{text.encode(@encoding, invalid: :replace, undef: :replace)}"
  response = send_command(CMD_WRITE_LCD, command_string)

  raise RBZK::ZKErrorResponse, "Can't write lcd" unless response && response[:status]

  true
end