usbscale 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #!/usr/bin/env perl
  2. #
  3. # Eric Jiang
  4. # http://notes.ericjiang.com/posts/54
  5. # This software is public domain.
  6. #
  7. # NOTE: This code is not maintained!
  8. # There is a newer version written in C:
  9. # https://github.com/erjiang/usbscale
  10. #
  11. use bytes;
  12. my $data;
  13. #prevents us from repeating messages
  14. my $waitingflag = 0;
  15. while (1) {
  16. $data = `cat /dev/hidraw7 | head -c 7`;
  17. my $report = ord(substr($data, 0, 1));
  18. my $status = ord(substr($data, 1, 1));
  19. my $unit = ord(substr($data, 2, 1));
  20. my $exp = ord(substr($data, 3, 1));
  21. my $lsb = ord(substr($data, 4, 1));
  22. my $msb = ord(substr($data, 5, 1));
  23. my $weight = ($msb * 256 + $lsb) / 10;
  24. if($exp != 255 && $exp != 0) {
  25. $weight ^= $exp;
  26. }
  27. #print "$report $status $unit $exp $weight\n";
  28. if($report != 0x03) {
  29. die "Error reading scale data!\n";
  30. }
  31. if($status == 0x01) {
  32. die "Scale reports FAULT!\n";
  33. } elsif ($status == 0x02 || $weight == 0) {
  34. if($waitingflag != 0x02) {
  35. print "Zero'd...\n";
  36. $waitingflag = 0x02;
  37. }
  38. } elsif ($status == 0x03) {
  39. if($waitingflag != 0x03) {
  40. print "Weighing...\n";
  41. $waitingflag = 0x03;
  42. }
  43. } elsif ($status == 0x04) {
  44. my $unitName = "units";
  45. if($unit == 11) {
  46. $unitName = "ounces";
  47. } elsif ($unit == 12) {
  48. $unitName = "pounds";
  49. }
  50. print "$weight $unitName\n";
  51. last;
  52. } elsif ($status == 0x05) {
  53. if($waitingflag != 0x05) {
  54. print "Scale reports Under Zero...\n";
  55. $waitingflag = 0x05;
  56. }
  57. } elsif ($status == 0x06) {
  58. if($waitingflag != 0x06) {
  59. print "Scale reports Over Weight!\n";
  60. $waitingflag = 0x06;
  61. }
  62. } elsif ($status == 0x07) {
  63. if($waitingflag != 0x07) {
  64. print "Scale reports Calibration Needed!\n";
  65. $waitingflag = 0x07;
  66. }
  67. } elsif ($status == 0x08) {
  68. if($waitingflag != 0x08) {
  69. print "Scale reports Re-zeroing Needed!\n";
  70. $waitingflag = 0x08;
  71. }
  72. } else {
  73. die "Unknown status code: $status\n";
  74. }
  75. }